【问题标题】:H2 driver can't find/create a tableH2 驱动程序找不到/创建表
【发布时间】:2013-10-21 13:51:57
【问题描述】:

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

【问题讨论】:

  • 如果表是自己创建的,那就太神奇了。
  • H2 如果表不存在则创建表,或者如果连接 url 中提供的 DATABASE 不存在则创建表?我赌第二个。

标签: java jdbc prepared-statement h2 sqlexception


【解决方案1】:

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

创建表格动物 ( animal_type_id 整数, 动物名称 varchar(255) );

【讨论】:

  • 啊啊啊啊啊!不敢相信我错过了那个。所有的工作和没有游戏使 Ticketmonster 成为一个愚蠢的编码器。只工作不玩......
猜你喜欢
  • 2019-10-23
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 2020-05-30
相关资源
最近更新 更多