我想创建表并在其中插入一些值。我正在尝试使用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语句是正确的,列的名称和类型相互匹配,我真的无法理解是什么问题。
答案 0 :(得分:3)
现有的PERSONS表与CREATE TABLE IF NOT EXISTS语句中的结构不匹配。删除并重新创建表解决了这个问题。