我在Java中使用JDBC创建了与SQLite的数据库连接。我的SQL语句正确执行,但有时在使用conn.commit()
时出现以下错误:
java.sql.SQLException: SQL logic error or missing database
任何人都可以帮助我如何避免这类问题。有没有更好的方法来调用JDBC程序?
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:/home/Data/database.db3");
conn.setAutoCommit(false);
String query = "Update Chits set BlockedForChit = 0 where ServerChitID = '" + serverChitId + "' AND ChitGatewayID = '" + chitGatewayId + "'";
Statement stmt = conn.createStatement();
try {
stmt.execute(query);
conn.commit();
stmt.close();
stmt = null;
}
答案 0 :(得分:2)
你的变量serverChitId& chitGatewayId包含会破坏SQL的字符?使用PreparedStatements通常更安全:
PreparedStatement ps = conn.prepareStatement("Update Chits set BlockedForChit = 0 where ServerChitID = ? AND ChitGatewayID = ?");
ps.setString(1, serverChitId);
ps.setString(2, chitGatewayId);
ps.executeUpdate();
这样JDBC驱动程序负责确保对字符串进行必要的转义。