java-在sql2o中插入时出错

我想创建表并向其中插入一些值.我正在尝试使用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();
        }
    }
}

毕竟我得到一个错误:

Error preparing statement – Column count does not match; SQL
statement: insert into PERSONS values (?, ?) [21002-191]

SQL语句是正确的,列的名称和类型彼此匹配,我真的不明白问题出在哪里.

解决方法:

现有的PERSONS表与CREATE TABLE IF NOT EXISTS语句中的结构不匹配.删除并重新创建表可以解决该问题.

上一篇:一个空的结果集上的Spring Data JPA聚合函数


下一篇:java-H2服务器在调试时挂起