Java JDBC PreparedStatement外键约束失败

时间:2015-05-14 16:07:49

标签: java sqlite jdbc prepared-statement

我正在使用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,date,attorney和notes,其中id设置为autoincrement,律师是律师表的外键。我传入的律师名称实际上存在于律师的席位中。

当我使用常规语句时,这在以前的构建期间工作正常,但是现在我已经交换到准备好的语句,我得到了这个:

Error updating database: [SQLITE_CONSTRAINT] Abort due to constraint violation (FOREIGN KEY constraint failed)

我不知道自己做错了什么。有什么建议?

4 个答案:

答案 0 :(得分:1)

包装参数的其他单引号可能导致FK违规。在循环中使用它:

statement.setString(i+1, inserters[i]);

您可能还需要从insert语句中删除分号。

答案 1 :(得分:0)

李,

你可以尝试最后删除分号,如下所示 “插入时间表(日期,律师,备注)值(?,?,?)”

答案 2 :(得分:0)

同时验证律师名称是否与律师的表格完全相同,有时我们会忘记案例敏感性

答案 3 :(得分:0)

您的preparedInsert方法似乎正在创建问题。尝试改变它,如下面

PreparedStatement statement = c.prepareStatement(query);

<script>
$(document).ready(function() {
    data = [{
        "id": "all",
        "text": "All",
        "children": [{
            "id": "item1",
            "text": "item1"
        }, {
            "id": "item2",
            "text": "item2"
        }]
    }];

    $(".select2-text").select2({
        "data": data
    });
});
</script>
<select class="select2-text"></select>