默认情况下,SQLite 似乎不强制执行外键。我在用着sqlitejdbc-v056.jar http://www.zentus.com/sqlitejdbc/我读过使用PRAGMA foreign_keys = ON;
将打开外键约束,并且需要在每个连接的基础上打开。
我的问题是:我需要执行哪些Java语句来打开这个命令?我试过了:
connection.createStatement().execute("PRAGMA foreign_keys = ON");
and
Properties properties = new Properties();
properties.setProperty("PRAGMA foreign_keys", "ON");
connection = DriverManager.getConnection("jdbc:sqlite:test.db", properties);
and
connection = DriverManager.getConnection("jdbc:sqlite:test.db;foreign keys=true;");
但这些都不起作用。我在这里缺少什么吗?
我见过这个答案 https://stackoverflow.com/questions/4254371/enabling-foreign-key-constraints-in-sqlite-through-c-sharp我想做同样的事情,只使用 JDBC。
代码如下:
DriverManager.getConnection("jdbc:sqlite:some.db;foreign keys=true;")
不起作用。
你必须创建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;
}
这段代码取自this http://code-know-how.blogspot.ru/2011/10/how-to-enable-foreign-keys-in-sqlite3.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)