无法使用Java在sqlite中添加外键约束

时间:2018-12-16 14:31:46

标签: java database sqlite jdbc

我的桌子是:

Statement s5 = conn.createStatement();
             ResultSet res5 = s5.executeQuery("Select name from sqlite_master where type = 'table' and name = 'actor_director'");
             if(!res5.next()){
                Statement ad = conn.createStatement();
                ad.executeUpdate("create table actor_director(actor_ID integer, director_ID integer," 
                        + "foreign key(actor_ID) references actor(actor_ID) ON UPDATE CASCADE ON DELETE CASCADE," 
                        + "foreign key(director_ID) references director(director_ID)) ON UPDATE CASCADE ON DELETE CASCADE"); 

             }

我也做了:

public static Connection getConnection() throws SQLException{
    SQLiteConfig config = new SQLiteConfig();  
    config.enforceForeignKeys(true);
    conn = DriverManager.getConnection("jdbc:sqlite:movieandtvseries.db", config.toProperties());
    return conn;
}

运行程序时出现此错误:

SQLiteException: [SQLITE_ERROR] SQL error or missing database (near "ON": syntax error)

1 个答案:

答案 0 :(得分:0)

您似乎在该行中有一个错字:

          + "foreign key(director_ID) references director(director_ID)) ON UPDATE CASCADE ON DELETE CASCADE");

在“ director_ID”之后还有一个额外的“)”。在最后一个“ CASCADE”之后和双引号之前还缺少一个“)”。