我正在使用 SQLite 和 JDBC 设计一个计费程序,并且我正在尝试使用此辅助方法:
public static void preparedInsert(String query, String[] inserters) {
Connection c = connect();
try {
PreparedStatement statement = c.prepareStatement(query);
for (int i = 0; i < inserters.length; i++) {
statement.setObject(i + 1, "\'" + inserters[i] + "\'");
}
statement.executeUpdate();
c.commit();
JOptionPane.showMessageDialog(null, "Database updated!");
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error updating database: " + e.getMessage());
}
disconnect(c);
}
public static Connection connect() {
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
c = DriverManager.getConnection("jdbc:sqlite:MRWBilling.db", config.toProperties());
c.setAutoCommit(false);
} catch ( Exception e ) {
JOptionPane.showMessageDialog(null, "Error connecting to database: " + e.getMessage());
}
return c;
}
public static void disconnect(Connection c) {
try {
c.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error disconnecting from database: " + e.getMessage());
}
}
我试图传入的参数是这样的:
SQLiteJDBC.preparedInsert("insert into timesheets(date, attorney, notes) values(?, ?, ?);",
new String[]{date, attorneyName, notes});
Timesheets 有四行:id、日期、律师和注释,其中 id 设置为自动增量,律师是律师表的外键。我传入的律师姓名实际上存在于律师表中。
在之前的构建过程中,当我使用常规语句时,这工作得很好,但现在我已经切换到准备好的语句,我得到了这个:
Error updating database: [SQLITE_CONSTRAINT] Abort due to constraint violation (FOREIGN KEY constraint failed)
我不知道自己做错了什么。有什么建议么?
最佳答案
包裹参数的额外单引号可能导致 FK 冲突。在循环中使用它:
statement.setString(i+1, inserters[i]);
您可能还需要从 insert
语句中删除分号。
关于Java JDBC PreparedStatement 外键约束失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30242018/