H2 can create database if not exist. But you need to create tables by yourself using SQL Go ahead with
CREATE TABLE animals ( animal_type_id int, animal_name varchar(255) );
Вопрос
I have the following query that I'm trying to execute against a local/embedded 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.
}
}
}
When I run this, I get the following exception:
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)
Line 23 of SQLExecutor
is:
preppedStatement = connection.prepareStatement(statement.getStatement());
I was told that H2 will create a table if none existed, so I'm confused as to why its telling me that the table isn't found - shouldn't it just be created? Thanks in advance!
Решение
H2 can create database if not exist. But you need to create tables by yourself using SQL Go ahead with
CREATE TABLE animals ( animal_type_id int, animal_name varchar(255) );