【发布时间】:2015-05-14 16:07:48
【问题描述】:
我正在使用 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)
我不知道自己做错了什么。有什么建议么?
【问题讨论】:
标签: java sqlite jdbc prepared-statement