【发布时间】:2016-05-14 14:42:32
【问题描述】:
我想创建表并在其中插入一些值。我正在尝试在下面的代码中使用 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语句正确,列的名称和类型相互匹配,实在看不懂是什么问题。
【问题讨论】:
-
我无法重现您的问题。我使用 H2 和 sql2o 的最新生产版本将您的代码复制并粘贴到 Maven 项目中,它运行良好。尝试删除您的 H2 数据库文件或在代码开头发出
DROP TABLE PERSONS。 -
哦,我真的忘记放下桌子了!谢谢,现在可以了!