我尝试对本地/嵌入式 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 将创建一个表,所以我很困惑为什么它告诉我没有找到该表-不应该创建它吗?提前致谢!