我有以下查询,我正在尝试对本地/嵌入式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)
SQLExecutor
的第23行是:
preppedStatement = connection.prepareStatement(statement.getStatement());
有人告诉我H2会创建一个表,如果不存在,所以我很困惑为什么它告诉我找不到表 - 不应该只创建它吗?提前谢谢!
答案 0 :(得分:1)
H2可以创建数据库(如果不存在)。但是您需要使用SQL自己创建表 继续
CREATE TABLE动物 ( animal_type_id int, animal_name varchar(255) );