代码之家  ›  专栏  ›  技术社区  ›  user1768830

H2驱动程序无法找到/创建表

  •  0
  • user1768830  · 技术社区  · 11 年前

    我正在尝试对本地/嵌入式H2 DB执行以下查询:

    String sql = "INSERT INTO animals ( animal_name, animal_type_id ) VALUES ( 'Dog', 34 )";
    sqlExecutor.doSQL(sql);
    
    // SQLExecutor.java
    public class SQLExecutor {
        private static final String DRIVER_CLASS = "org.h2.Driver";
        private static final String CONNECTION_URL = "jdbc:h2:~/.myapp/data/myapp_db;DB_CLOSE_DELAY=-1";
        private static final String DB_USER = "myuser";
        private static final String DB_PASSWORD = "mypasswd";
    
        public void doSQL(String sql) {
            Connection connection = null;
            PreparedStatement preppedStatement = null;
            ConnectionPool connectionPool = new ConnectionPool(DRIVER_CLASS, CONNECTION_URL, DB_USER, DB_PASSWORD);
    
            try {
                connection = connectionPool.borrow();
                preppedStatement = connection.prepareStatement(statement.getStatement());
    
                preppedStatement.executeUpdate();
    
                connection.commit();
            } catch(Throwable throwable) {
                logger.error(ExceptionUtils.getStackTrace(throwable));
                throw new RuntimeException(throwable);
            } finally {
                // Close result set, prepped statement, return connection, etc.
            }
        }
    }
    

    当我运行此程序时,我会得到以下异常:

    Exception in thread "main" java.lang.RuntimeException: org.h2.jdbc.JdbcSQLException: Table "ANIMALS" not found; SQL statement:
    INSERT INTO animals ( animal_name, animal_type_id ) VALUES ( ?, ? );  [42102-173]
        at net.myapp.core.SQLExecutor.doSQL(SQLExecutor.java:23)
    

    第23行,共23行 SQLExecutor 是:

    preppedStatement = connection.prepareStatement(statement.getStatement());
    

    有人告诉我,如果H2不存在,它会创建一个表,所以我很困惑,为什么它会告诉我找不到表——难道不应该创建它吗?提前谢谢!

    1 回复  |  直到 11 年前
        1
  •  1
  •   Bitman    11 年前

    如果不存在,H2可以创建数据库。但是您需要使用SQL自己创建表 继续

    创造餐桌动物 ( animal_ type_, animal_name varchar(255) );