0

我尝试对本地/嵌入式 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 行SQLExecutor是:

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

有人告诉我,如果没有表,H2 将创建一个表,所以我很困惑为什么它告诉我没有找到该表-不应该创建它吗?提前致谢!

4

1 回答 1

1

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

创建表动物(animal_type_id int,animal_name varchar(255));

于 2013-10-21T13:55:25.127 回答