gpt4 book ai didi

java - JDBCPreparedStatement.setString() 无法与 SQLite 一起正常工作?

转载 作者:行者123 更新时间:2023-12-01 18:36:00 25 4
gpt4 key购买 nike

我正在使用 Xerials SQLite JDBC 驱动程序,并且想要做您能想象到的最简单的事情:

我创建了下表:

CREATE TABLE IF NOT EXISTS households (hostname_id_pk INTEGER PRIMARY KEY, hostname TEXT UNIQUE, vm TEXT);

现在,因为我想要一个参数化的插入语句,所以我使用PreparedStatment,如下所示:

public static void main(String[] args) throws ClassNotFoundException {
Class.forName("org.sqlite.JDBC");
Connection con = null;
PreparedStatement updateHouseholdStmt = null;

try {
con = DriverManager.getConnection(DB_IDENTIFIER);

String getHouseholdString = "SELECT hostname_id_pk FROM households WHERE hostname = ?";
String updateHouseholdString = "INSERT INTO households (hostname, vm) values(?, 'VM1')";

getHouseholdStmt = con.prepareStatement(getHouseholdString);
getHouseholdStmt.setString(1, "test1");

updateHouseholdStmt = con.prepareStatement(updateHouseholdString);
getHouseholdStmt.setString(1, "test1");

ResultSet hhRS = getHouseholdStmt.executeQuery();
int hhId = -1;

if(hhRS.next()){
hhId = hhRS.getInt(1);
System.out.println(hhId);
} else {
System.out.println(updateHouseholdStmt.executeUpdate());
}

} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
try {
if (con != null) {
con.close();
}
if (getHouseholdStmt != null){
getHouseholdStmt.close();
}
if (updateHouseholdStmt != null) {
updateHouseholdStmt.close();
}
} catch (SQLException e) {
System.err.println(e);
}
}

}

在这种情况下,我在数据库中唯一能找到的是一个带有 (1, , VM1) 的新条目,这意味着该条目已创建,但由于某种原因缺少字符串参数.

当我替换“?”时在 updateHousholdStatement() 中使用示例值并删除 .setString(...) 方法行,一切正常。

我到底错过了什么?!今天早上我已经检查了一千遍了。

提前谢谢。

最佳答案

请更正以下行:

updateHouseholdStmt = con.prepareStatement(updateHouseholdString);
getHouseholdStmt.setString(1, "test1");

updateHouseholdStmt = con.prepareStatement(updateHouseholdString);
updateHouseholdStmt.setString(1, "test1");

关于java - JDBCPreparedStatement.setString() 无法与 SQLite 一起正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21989816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com