如何通过Java在SQLite中强制执行外键约束?

Zar*_*jio 15 java sqlite jdbc foreign-keys

看来SQLite默认不强制执行外键.我正在使用sqlitejdbc-v056.jar并且我已经读过使用PRAGMA foreign_keys = ON;将打开外键约束,并且需要在每个连接的基础上打开它.

我的问题是:我需要执行哪些Java语句来打开此命令?我试过了:

connection.createStatement().execute("PRAGMA foreign_keys = ON");
Run Code Online (Sandbox Code Playgroud)

Properties properties = new Properties();
properties.setProperty("PRAGMA foreign_keys", "ON");
connection = DriverManager.getConnection("jdbc:sqlite:test.db", properties);
Run Code Online (Sandbox Code Playgroud)

connection = DriverManager.getConnection("jdbc:sqlite:test.db;foreign keys=true;");
Run Code Online (Sandbox Code Playgroud)

但这些都不起作用.这里有什么我想念的吗?

我已经看到了这个答案,我想做同样的事情,只使用JDBC.

Che*_*rry 31

像这样的代码:

DriverManager.getConnection("jdbc:sqlite:some.db;foreign keys=true;")
Run Code Online (Sandbox Code Playgroud)

不行.org.sqlite.SQLiteConfig从DriverManager调用getConnection时,必须创建并将其设置为属性.

public static final String DB_URL = "jdbc:sqlite:database.db";  
public static final String DRIVER = "org.sqlite.JDBC";  

public static Connection getConnection() throws ClassNotFoundException {  
    Class.forName(DRIVER);  
    Connection connection = null;  
    try {  
        SQLiteConfig config = new SQLiteConfig();  
        config.enforceForeignKeys(true);  
        connection = DriverManager.getConnection(DB_URL,config.toProperties());  
    } catch (SQLException ex) {}  
    return connection;  
}
Run Code Online (Sandbox Code Playgroud)

这段代码取自.


Chr*_*ipp 16

当你查看SQLite外键支持页面时,我会解释它

  1. 必须使用外键支持编译SQLlite
  2. 您仍然必须为PRAGMA的每个连接打开它
  3. 创建表时,必须将外键定义为约束

广告1)引自此处:

如果命令"PRAGMA foreign_keys"不返回任何数据而不是包含"0"或"1"的单行,那么您使用的SQLite版本不支持外键(因为它超过3.6.19或因为它编译时使用SQLITE_OMIT_FOREIGN_KEY或SQLITE_OMIT_TRIGGER定义).

你的结果是PRAGMA foreign_keys;什么?

更新:从你的评论我看到你正在使用3.6.14.2,这意味着你的版本不支持外键约束!所以你必须更新SQLite,如果可能的话!

广告2)您的第一个代码段执行PRAGMA语句,我认为这不会起作用.第三个剪辑根据你的评论不起作用:SQLite驱动程序将整个字符串解释为数据库的位置,而不是将"foreign keys = true"部分作为连接设置".所以只有第二个片段才有效.

广告3)您是否创建了具有外键支持的表?引自这里:

CREATE TABLE artist(
  artistid    INTEGER PRIMARY KEY, 
  artistname  TEXT
);
CREATE TABLE track(
  trackid     INTEGER, 
  trackname   TEXT, 
  trackartist INTEGER,
  FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);
Run Code Online (Sandbox Code Playgroud)


cbh*_*edd 5

不幸的是,我无法对上一张海报的答案发表评论,但作为对可能来到这里的其他人的提示,第一个代码片段:

connection.createStatement().execute("PRAGMA foreign_keys = ON");
Run Code Online (Sandbox Code Playgroud)

当您的 SQLite 版本是最新的并且支持外键支持时,绝对可以工作。


lsh*_*lsh 5

此页面在翻译为 Clojure 时很有帮助,但我的解决方案不同。因此,对于后代,即使 OP 要求使用 Java,我在 Clojure 中也是这样做的:

(def db-spec {:connection-uri "jdbc:sqlite:db.sqlite3?foreign_keys=on;"})