It appears that SQLite does not enforce foreign keys by default. I'm using sqlitejdbc-v056.jar and I've read that using PRAGMA foreign_keys = ON;
will turn on foreign key constraints, and that this needs to be turned on in a per-connection basis.
My question is: what Java statements do I need to execute to turn on this command? I've tried:
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;");
but none of those work. Is there something I am missing here?
I've seen this answer and I want to do exactly the same thing, only using JDBC.
SQLite has supported foreign key constraint since version 3.6. 19.
How to Add a Foreign Key to an Existing Table. You can not use the ALTER TABLE statement to add a foreign key in SQLite. Instead you will need to rename the table, create a new table with the foreign key, and then copy the data into the new table.
The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.
Code like this:
DriverManager.getConnection("jdbc:sqlite:some.db;foreign keys=true;")
Does not work.
You have to create org.sqlite.SQLiteConfig
and set it as properties when call getConnection from DriverManager.
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 code taken from this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With