SQLite Delete Cascade not working: FOREIGN KEY constraint failed - java

I have two table:
Child Table
public static final String SQL_CREATE_TAB_COMMENT = "CREATE TABLE " +TABLE_COMMENT+ "( " + KEY_COMMENT + " INTEGER PRIMARY KEY AUTOINCREMENT , " + COLUMN_EMMET + " TEXT NOT NULL , " +COMMENT+ " TEXT , "+IMAGCOM+" TEXT , "+FORMAT+" TEXT NOT NULL , "+DATECMTCREATION+" TEXT , "+TAGSTATUTCMT+" TEXT , "+ COLUMN_COMMENT_KEY_POST +" INT NOT NULL , "+EMETPOST_PHONE+ " TEXT, " +DEST_PHONE+ " TEXT, " + IDCMTEMET + " TEXT,"+VISITEDCMT+" TEXT, "+TAB_IMAGES + " TEXT, "+IS_DOWNLOADED + " TEXT,"+FILEDOC+" TEXT, FOREIGN KEY(" + COLUMN_COMMENT_KEY_POST + ") REFERENCES " + TABLE_POST_NEW + "(_id) ON DELETE CASCADE )";
Parent Table
public static final String SQL_CREATE_TAB_POST_NEW = "CREATE TABLE " +TABLE_POST_NEW+ "( " +KEY_POST+ " INTEGER PRIMARY KEY AUTOINCREMENT ," +EMMET+ " TEXT NOT NULL , " +TEXT+ " TEXT NOT NULL , "+ IMAG +" TEXT ,"+TYPE+ " TEXT ," +DEST+ " TEXT ," +IDPOSTEMET+ " TEXT NOT NULL, " +CMT_NON_LU+ " TEXT, " +DATELASTEVENT+" TEXT, " +DATECREATION+ " TEXT, " +TAGSTATUT+ " TEXT,"+COUNTER_DEST+" TEXT,"+VISITED+" TEXT,"+ NAME_GROUP+ " TEXT,"+ IDGROUP + " TEXT, "+TAB_IMAGES + " TEXT, "+IS_DOWNLOADED +" TEXT, "+COLUMN_POST_KEY_CONTACT+ " INT NOT NULL DEFAULT 0, "+LABEL_IMAGES+" TEXT,"+TAB_FILE+" TEXT)";
Now If I am deleting parent row I have this error:
FOREIGN KEY constraint failed Error Code : 787 (SQLITE_CONSTRAINT_FOEIGNKEY)
Caused By : Abort due to constraint violatio
public PosteManager openForWrite(){
db = dbHelper.getWritableDatabase();
//db.execSQL("PRAGMA foreign_keys=ON");
db.setForeignKeyConstraintsEnabled(true);
return this;
}
public int deletePoste(int posteId){
openForWrite();
int delete = db.delete(DbHelper.TABLE_POST_NEW, DbHelper.KEY_POST + "=" + posteId, null);
close();
return delete;
}
KEY_POST = _id; and I test COLUMN_COMMENT_KEY_POST = _id and COLUMN_COMMENT_KEY_POST = post_id
I have the same error
I test your code and I have this in Log.d("TABLESQL","The creation SQL for table " :
D/TABLESQL: The creation SQL for table comment_tbl_new is
CREATE TABLE comment_tbl_new( _commentid INTEGER PRIMARY KEY AUTOINCREMENT , Emetteur TEXT NOT NULL , comment TEXT , imageCom TEXT , format TEXT NOT NULL , Datecmtcreation TEXT , Tagstatutcmt TEXT , post_id INT NOT NULL , emetPost_phone TEXT, Dest_phone TEXT, idcmtemet TEXT,visited TEXT, tab_image TEXT, idownloaded TEXT,filedoc TEXT, FOREIGN KEY(post_id) REFERENCES post_tbl_new(_id) )
06-14 00:11:06.845 18468-18468/com. D/TABLESQL: The creation SQL for table comment_tbl is
CREATE TABLE comment_tbl( _commentid INTEGER PRIMARY KEY AUTOINCREMENT , Emetteur TEXT NOT NULL , comment TEXT , imageCom TEXT , format TEXT NOT NULL , Datecmtcreation TEXT , Tagstatutcmt TEXT , _id INT NOT NULL , emetPost_phone TEXT, Dest_phone TEXT, idcmtemet TEXT,visited TEXT, tab_image TEXT, idownloaded TEXT,filedoc TEXT, FOREIGN KEY(_id) REFERENCES post_tbl_new(_id) ON DELETE CASCADE )

From API 16+, you should enable foreign key constraint like this in SQLITEOpenHelper class:
#Override
public void onConfigure(SQLiteDatabase db){
db.setForeignKeyConstraintsEnabled(true);
}
As the foreign key constraint is enabled, You can check if another table is not referring child table and it's foreign key is not cascade. Also ") REFERENCES " + TABLE_POST_NEW + "(_id) have you defined _id column in your TABLE_POST_NEW ?

Related

Database does not store data. I get the "SQLiteLog: (1) near "Name": syntax error" from Android Studio log

I get from "SQLiteLog: (1) near "Name": syntax error" after the addPatient() method is called and the data given by addPatient() method is not stored in the database.
At first, I suspect that something might be wrong with my "CREATE TABLE" query but I have tried everything and I couldn't figure out what was wrong.
#Override
public void onCreate(SQLiteDatabase db)
{
//===============Create a table for Patient
String query = "CREATE TABLE TABLE_PATIENT (COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"COLUMN_USERNAME TEXT, " +
"COLUMN_PASSWORD TEXT, " +
"COLUMN_FIRSTNAME TEXT, " +
"COLUMN_LASTNAME TEXT, " +
"COLUMN_AGE TEXT, " +
"COLUMN_GENDER TEXT, " +
"COLUMN_PHONE TEXT, " +
"COLUMN_ADDRESS TEXT);";
db.execSQL(query);
}//End of onCreate()
//Add a new Patient Row to the database
public void addPatient(Patient patient)
{
Log.i(TAG, "addPatient("+patient.getUserName()+")");
ContentValues values = new ContentValues();
values.put(COLUMN_ID, patient.getU_Id());
values.put(COLUMN_USERNAME, patient.getUserName());
values.put(COLUMN_PASSWORD, patient.getPassword());
values.put(COLUMN_FIRSTNAME, patient.getFirstName());
values.put(COLUMN_LASTNAME,patient.getLastName());
values.put(COLUMN_AGE, patient.getAge());
values.put(COLUMN_GENDER,patient.getGender());
values.put(COLUMN_PHONE,patient.getPhoneNumber());
values.put(COLUMN_ADDRESS, patient.getAddress());
SQLiteDatabase db = getWritableDatabase();
try
{
db.insert(TABLE_PATIENT, null, values);
db.close();
}catch (Exception e)
{
Log.i(TAG, e.getMessage());
}
}//End of addPatient()
I guess you have defined these variables:
String COLUMN_ID = "id";
String COLUMN_USERNAME = "username";
....................................
or something like that.
If you have spaces in the names of the columns you must use square brackets or backticks around them, like:
String COLUMN_USERNAME = "[user name]";
In your CREATE TABLE statement you define the column names as:
"COLUMN_ID", "COLUMN_USERNAME", ....
because you use the variable names and not their values.
But in addPatient() method you are putting values to the ContentValues object by using their actual names.
To solve your problem, 1st uninstall the app from the device you are testing it, so the database is deleted.
Then change the CREATE TABLE statement like this:
String query = "CREATE TABLE " + TABLE_PATIENT +" (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_USERNAME + " TEXT, " +
COLUMN_PASSWORD + " TEXT, " +
COLUMN_FIRSTNAME + " TEXT, " +
COLUMN_LASTNAME + " TEXT, " +
COLUMN_AGE + " TEXT, " +
COLUMN_GENDER + " TEXT, " +
COLUMN_PHONE + " TEXT, " +
COLUMN_ADDRESS + " TEXT)";
and rerun to recreate the database with the correct column names.

Why is sqlite auto_increment not incrementing?

I've got a database set up to store notes. I want to auto increment the first column. I've tried this, but when I read from the database every result in that column is 'null'.This is the code for creating the DB.
private static final String NOTES_TABLE_CREATE =
"CREATE TABLE " + NOTES_TABLE_NAME + " (" +
COLUMN_NAMES[0] + " INTEGER AUTO_INCREMENT, " +
COLUMN_NAMES[1] + " TEXT, " +
COLUMN_NAMES[2] + " TEXT, " +
COLUMN_NAMES[3] + " TEXT, " +
COLUMN_NAMES[4] + " TEXT, " +
COLUMN_NAMES[5] + " TEXT, " +
COLUMN_NAMES[6] + " TEXT);";
This is the code for getting the DB result.
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.query(NOTES_TABLE_NAME, COLUMN_NAMES, null, null, null, null, null, null);
result.moveToFirst();
result.moveToNext();
System.out.println(result.getInt(0));
System.out.println(result.getString(1));
This is the output from logcat
04-09 17:56:17.981 22147-22147/com.example.a8460p.locationotes I/System.out: 0
04-09 17:56:17.981 22147-22147/com.example.a8460p.locationotes I/System.out: notetitle1234567890
AUTO_INCREMENT (as opposed to INTEGER PRIMARY KEY AUTOINCREMENT) is not supported in sqlite.
This is a little non-obvious, because sqlite silently ignores column constraints it does not recognize:
sqlite> CREATE TABLE test (
a INTEGER FABBELBABBEL NOT NULL
);
sqlite> .schema test
CREATE TABLE test (a INTEGER FABBELBABBEL NOT NULL);
sqlite> INSERT INTO test (a) VALUES (1);
sqlite> INSERT INTO test (a) VALUES (NULL);
Error: NOT NULL constraint failed: test.a
AUTOINCREMENT on the other hand, is supported for integer primary keys and only there, so the obvious workaround attempt is not supported, either:
sqlite> CREATE TABLE test (a INTEGER AUTOINCREMENT NOT NULL, b INTEGER);
Error: near "AUTOINCREMENT": syntax error
In short: Auto increment is only available for integer primary keys.

How can I set primary key in particular text field?

My Code here
db.execSQL("create table if not exists data(patient_name varchar,patient_id INTEGER PRIMARY KEY ,patient_phone varchar,patient_mail varchar,patient_age,patient_gender varchar,patient_address varchar,patient_lvd varchar,patient_nvd varchar,patient_notes varchar)");
Try this way,
String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "
+ DATABASE_TABLE + "("
+ patient_id + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ patient_phone + " TEXT, "
+ patient_name + " TEXT, "
+ patient_phone + " TEXT )";
db.execSQL(CREATE_TABLE);
You can follow SQLite Database Tutorial

Inserting in the sqlite with exesql

i need a tip here , here i have a code to insert into sqlite database:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
String sqlCreate = "CREATE TABLE IF NOT EXISTS " + name
+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " Type TEXT,"
+ " Text TEXT,"
+ " OtherFormats TEXT,"
+ " Date TEXT,"
+ " Image TEXT,"
+ " RealName TEXT)";
db.execSQL(sqlCreate);
//(String Type, String Text ,String name,String OtherFormats,String Itime,String
RealName)
String sqlInsert= "INSERT INTO " + "'"+name+"'" +
" VALUES
("+"'"+ID+"'"+","+"'"+Type+"'"+","+"'"+Text+"'"+","+
"'"+OtherFormats+"'"+","+"'"+Date+"'"+"
,"+"'"+Image+"'"+","+"'"+RealName+"')";
db.execSQL(sqlInsert);
}
});
t.start();
the question is as you u see my ID is auto increment, but for executing it well, i need to put a value there,what value should i put so it database does the increament itself?
thanks
05-26 03:56:33.018: E/AndroidRuntime(23809):
android.database.sqlite.SQLiteException: near "VALUES": syntax error (code 1): ,
while compiling: INSERT INTO 'new' (Type,Text,OtherFormats ,Date,Image,RealName VALUES('m','hey','n','03:56','j','s')
You can do this. Enter the name of columns you need to insert
String sqlInsert= "INSERT INTO " + "'"+name+"' (Type,Text,OtherFormats ,Date,Image,RealName )VALUES
("+"'"+ID+"'"+","+"'"+Type+"'"+","+"'"+Text+"'"+","+
"'"+OtherFormats+"'"+","+"'"+Date+"'"+"
,"+"'"+Image+"'"+","+"'"+RealName+"')";
db.execSQL(sqlInsert);
the question is as you u see my ID is auto increment, but for executing it well, i need to put a value there,what value should i put so it database does the increament itself?
Put in a NULL or just leave it unspecified.
From the documentation:
If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically.

ERROR ON QUERYING ORACLE DB

I am using oracle 10g and I wrote a create table query like this -
String UserTable="CREATE TABLE UserDetail ( \n" +
" idNo INT(64) NOT NULL , \n" +
" name VARCHAR(50),\n" +
" email VARCHAR(50), \n" +
" state VARCHAR(50),\n"+
" country VARCHAR(50),\n" +
" CONSTRAINT person_pk PRIMARY KEY ('idNo')"
+ ");";
// Connection con2=DriverManager.getConnection(DbAddress,"vivek","123456");
PreparedStatement st2=conn.prepareStatement(UserTable);
st2.executeUpdate();
conn.close();
but it gives following exception-
java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis
on syssout it the query becomes this -
CREATE TABLE UserDetail (
idNo INT(64) NOT NULL ,
name VARCHAR(50),
email VARCHAR(50),
state VARCHAR(50),
country VARCHAR(50),
CONSTRAINT person_pk PRIMARY KEY (idNo)
);
please help.
Remove the below line
CONSTRAINT person_pk PRIMARY KEY ('idNo')
Use the below line in your code instead
CONSTRAINT person_pk PRIMARY KEY (idNo)
oh I got the solution- I was using Int instead of Number and it was not supported. the query should be-
"CREATE TABLE UserDetail ( \n" +
" idNo NUMBER NOT NULL , \n" +
" name VARCHAR(50),\n" +
" email VARCHAR(50), \n" +
" state VARCHAR(50),\n"+
" country VARCHAR(50),\n" +
" CONSTRAINT person_pk PRIMARY KEY ('idNo')"
+ ");";

Categories