3

我想创建表并在其中插入一些值。我正在尝试在下面的代码中使用 H2 数据库和 sql2o 框架:

public class Main {

    private static final String DB_DRIVER = "org.h2.Driver";
    private static final String DB_CONNECTION = "jdbc:h2:~/test";
    private static final String DB_USER = "";
    private static final String DB_PASSWORD = "";
    static String TABLE = "PERSONS";
    static Sql2o sql2o;

    public static void main(String[] args) throws Exception, SQLException {
        sql2o = new Sql2o(DB_CONNECTION, DB_USER, DB_PASSWORD);
        createTable();
        insertIntoTable();
    }

    public static void createTable() {
        final String tableSql = "CREATE TABLE IF NOT EXISTS " + TABLE + " (id int, name varchar(255))";
        try (org.sql2o.Connection con = sql2o.beginTransaction()) {
            con.createQuery(tableSql).executeUpdate();
            con.commit();
            con.close();
        }
    }

    public static void insertIntoTable() {
        String insertSql = "insert into " + TABLE + " values (:id, :name)";
        try (org.sql2o.Connection con = sql2o.open()) {
            con.createQuery(insertSql).addParameter("id", 1).addParameter("name", "test").executeUpdate();
            con.close();
        }
    }
}

毕竟我得到一个错误:

准备语句时出错 - 列数不匹配;SQL 语句:插入 PERSONS 值 (?, ?) [21002-191]

SQL语句正确,列的名称和类型相互匹配,实在看不懂是什么问题。

4

1 回答 1

3

存在与 CREATE TABLE IF NOT EXISTS 语句中的结构不匹配的现有 PERSONS 表。删除并重新创建表解决了这个问题。

于 2016-05-16T03:05:10.460 回答