How can I set primary key in particular text field? - java

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

Related

SQLite Delete Cascade not working: FOREIGN KEY constraint failed

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 ?

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.

HttpReader OnResultReadyListener: attempt to re-open an already-closed object: SQLiteDatabase

I'm trying to convert a csv file that I get online and try to call a execSQL(String) based on the results.
The only problem is dat I send my SQLiteDatabase with my function in the parameter, but that way I can't acces it from within my resultReady(String result){} if I don't make the parameter final.
But when I make the SQLiteDatabase parameter final, I get the error message:
"attempt to re-open an already-closed object: SQLiteDatabase: ..."
Does anyone know how I could fix this?
The function:
private void insertTalen(SQLiteDatabase db) {
// lijst van alle talen met taalcode opgehaald van het internet
HttpReader httpReader = new HttpReader();
httpReader.setOnResultReadyListener(new HttpReader.OnResultReadyListener() {
#Override
public void resultReady(String result) {
CsvHelper csvHelper = new CsvHelper();
List<Taal> talen = csvHelper.getTalenFromCsv(result);
for (Taal taal: talen) {
String SQLScript = "INSERT INTO taal (engelseTaalNaam, taalCode) VALUES ('";
SQLScript += taal.getEngelseNaam();
SQLScript += "', '";
SQLScript += taal.getTaalCode();
SQLScript += "');";
db.execSQL(SQLScript);
}
}
});
httpReader.execute("https://raw.githubusercontent.com/datasets/language-codes/master/data/language-codes.csv");
}
And this function is called from my oncreate:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_TAAL = "CREATE TABLE taal (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"engelseNaam TEXT," +
"taalCode TEXT)";
db.execSQL(CREATE_TABLE_TAAL);
String CREATE_TABLE_GEBRUIKER = "CREATE TABLE gebruiker (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"highscoreGebruikerId INTEGER," +
"eigenTaalId INTEGER," +
"vreemdeTaalId INTEGER," +
"FOREIGN KEY (eigenTaalId) REFERENCES taal(id)," +
"FOREIGN KEY (vreemdeTaalId) REFERENCES taal(id))";
db.execSQL(CREATE_TABLE_GEBRUIKER);
String CREATE_TABLE_OPGESLAGEN_WOORD = "CREATE TABLE opgeslagenWoord (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"taalId INTEGER," +
"naam TEXT," +
"engelseVersieId INTEGER," +
"FOREIGN KEY (taalId) REFERENCES taal(id)," +
"FOREIGN KEY (engelseVersieId) REFERENCES opgeslagenWoord(id))";
db.execSQL(CREATE_TABLE_OPGESLAGEN_WOORD);
String CREATE_TABLE_GEKEND_WOORD = "CREATE TABLE gekendWoord (" +
"opgeslagenWoordId INTEGER PRIMARY KEY ," +
"datumverloopt TEXT," +
"niveauGekend INTEGER," +
"FOREIGN KEY (opgeslagenWoordId) REFERENCES opgeslagenWoord(id))";
db.execSQL(CREATE_TABLE_GEKEND_WOORD);
this.db = db;
insertTalen(db);
insertGebruiker(db);
}

Sqlite exception near "FOREIGN"?

String CREATE_SUBCATEGORY_TABLE = "CREATE TABLE " + TABLE_SUBCATEGORY_LIST+ "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + KEY_NAME + " TEXT,"
+ KEY_DESC + " TEXT,"+ KEY_CATEGORY_ID + " INTEGER,"
+ KEY_CONTENT1+" TEXT,"+ KEY_CONTENTTYPE1 + " TEXT,"
+ KEY_CONTENT2+" TEXT,"+ KEY_CONTENTTYPE2 + " TEXT,"
+ KEY_CONTENT3+" TEXT,"+ KEY_CONTENTTYPE3 + " TEXT,"
+ KEY_CONTENT4+" TEXT,"+ KEY_CONTENTTYPE4 + " TEXT,"
+ KEY_CONTENT5+" TEXT,"+ KEY_CONTENTTYPE5 + " TEXT,"
+ KEY_CONTENT6+" TEXT,"+ KEY_CONTENTTYPE6 + " TEXT,"
+ KEY_ORDERID+" INTEGER,"+ KEY_STATUS+" TEXT,"
+ KEY_UPDATED+" TEXT, FOREIGN KEY ("+KEY_CATEGORY_ID+") REFERENCES "+CAT_TABLE+"("+KEY_CATEGORY_ID+")";
I am getting the following error now:-
android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE subcategory_list(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,subcategory_name TEXT,subcategory_shdesc TEXT,category_id INTEGER,content1 TEXT,content_type1 TEXT,content2 TEXT,content_type2 TEXT,content3 TEXT,content_type3 TEXT,content4 TEXT,content_type4 TEXT,content5 TEXT,content_type5 TEXT,content6 TEXT,content_type6 TEXT,order_id INTEGER,status TEXT,updated TEXT, FOREIGN KEY (category_id) REFERENCES category_list(category_id)
Can anyone point out my mistake. Any help or suggestions are appreciated. Thank you.
Just fix some typos in the last line:
+ KEY_UPDATED + " TEXT," //added , and space
+" FOREIGN KEY (" + KEY_CATEGORY_ID + ") REFERENCES "
+ CAT_TABLE + "("+KEY_CATEGORY_ID+"))"; //added "CREATE TABLE closing parenthesis"
Add a Space before and a comma after "TEXT" in the last line.
You also have to close the last bracket.
Your last line would look correctly like this:
+ KEY_UPDATED+" TEXT," +" FOREIGN KEY ("+KEY_CATEGORY_ID+") REFERENCES "+CAT_TABLE+"("+KEY_CATEGORY_ID+"))";
You can also omit the " + " between TEXT and FOREIGN KEY, because you're just joining two strings.
+ KEY_UPDATED+" TEXT, FOREIGN KEY ("+KEY_CATEGORY_ID+") REFERENCES "+CAT_TABLE+"("+KEY_CATEGORY_ID+"))";

SQLite create dynamic table (or view?)

I have 3 tables:
Table.Keys, Table.Tags, Table.Values
Table.Keys create table statement:
createTableStatement = "CREATE TABLE " + Tables.KEYS + "("
+ KeysColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KeysColumns.KEY + " TEXT NOT NULL,"
+ "UNIQUE ("
+ KeysColumns.KEY
+ ") ON CONFLICT IGNORE"
+ ");";
execSQL(sqLiteDatabase, createTableStatement);
Table.Tags create table statement:
createTableStatement = "CREATE TABLE " + Tables.TAGS + " ("
+ TagsColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TagsColumns.NAME + " TEXT NOT NULL,"
+ "UNIQUE ("
+ TagsColumns.NAME
+ ") ON CONFLICT IGNORE"
+ ");";
execSQL(sqLiteDatabase, createTableStatement);
Table.Value create table statement:
createTableStatement = "CREATE TABLE " + Tables.VALUES + " ("
+ ValuesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ValuesColumns.KEY_ID + " TEXT NOT NULL,"
+ ValuesColumns.TAG_ID + " TEXT NOT NULL,"
+ ValuesColumns.VALUE + " TEXT NOT NULL,"
+ "UNIQUE ("
+ ValuesColumns.KEY_ID + ", " + ValuesColumns.TAG_ID
+ ") ON CONFLICT REPLACE"
+ ");";
execSQL(sqLiteDatabase, createTableStatement);
If I do the following join:
Tables.KEYS
+ " JOIN " + Tables.VALUES
+ " ON " + Values.KEY_ID + " = " + Keys.column(Keys._ID)
+ " JOIN " + Tables.TAGS
+ " ON " + Values.TAG_ID + " = " + Tags.column(Tags._ID);
I get duplicate rows of course because the result is
KEY | TAG | VALUE
=================
| |
What I would like to accomplish is to query and get a Cursor from table or view with no duplicate rows with the following schema:
KEY | TAG 1 | TAG 2 | ... | TAG n
=================================
| | | |
Not all keys MUST have values for each tag, but all keys CAN have values.
I'm not sure how to accomplish this. I'm not even sure where to start.
In the meantime I have created another table which stores some TAG values that I know will always exist.
But I feel this is inefficient because at any time I could have 'n' number of new TAG values which is why I would like to be able to create a view or table with the schema I listed.
SQLite has no pivot functions; you have to do this in two steps.
First, get all possible tags:
SELECT _id, Name
FROM Tags
ORDER BY Name;
Then, using the returned data, construct a query that looks up each possible tag for each key:
SELECT Key,
(SELECT Value
FROM Values
WHERE Key_ID = Keys._id
AND Tag_ID = 111
) AS Tag_111,
(SELECT Value
FROM Values
WHERE Key_ID = Keys._id
AND Tag_ID = 222
) AS Tag_222,
...
FROM Keys;

Categories