Whats wrong with my SQLite query? - android

Error:
android.database.sqlite.SQLiteException: near "-": syntax error (code 1): , while compiling: CREATE TABLE new_info(user-name TEXT,user_mob TEXT,user_email TEXT);
Code:
public String CREATE_QUERY="CREATE TABLE "+ UserContract.addnew.TABLE_NAME+"("+ UserContract.addnew.USER_NAME+" TEXT,"
+ UserContract.addnew.MOBILE+" TEXT,"+ UserContract.addnew.EMAIL+" TEXT);";

As you can see in the query it tries to execute: CREATE TABLE new_info(user-name TEXT,user_mob TEXT,user_email TEXT); You have - instead of _. Just replace user-name with user_name.
Check this post to understand how to be able to use hyphen in the table names.

Related

Flutter SQLite Syntax Error near TEXT decimal point

I can't seem to figure out what this syntax error is, I have tried TEXT & BLOB for both the mac & the image fields but nothing seems to work. Please help!
customQuery("CREATE TABLE Profile ("
"mac TEXT,"
"image TEXT,"
"name TEXT,"
"age INT,"
"nationality TEXT,"
"profession TEXT,"
"about TEXT"
")");
onPressed: () {
profile.add(Profile(
mac: _platformVersion,
image: imagePath,
name: nameController.text,
age: ageController.text,
nationality: nationalityController.text,
profession: professionController.text,
about: aboutController.text));
DBProvider.db.customQuery("INSERT Into Profile (mac,image,name,age,nationality,profession,about)"
" VALUES (${profile[0].mac},${profile[0].image},"
"${profile[0].name},${profile[0].age},${profile[0].nationality},"
"${profile[0].profession},${profile[0].about});");
},
& this is the error
E/SQLiteLog( 4520): (1) near ".0": syntax error in "INSERT Into Profile (mac,image,name,age,nationality,profession,about) VALUES (0.0.0.0.0.0,/data/user/0/com.test.fltestar/cache/scaled_image_picker3315305739073272987.jpg,test,35,test
E/flutter ( 4520): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: DatabaseException(near ".0": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT Into Profile (mac,image,name,age,nationality,profession,about) VALUES (0.0.0.0.0.0,/data/user/0/com.test.test/cache/scaled_image_picker3315305739073272987.jpg,test,35,test,test,test);) sql 'INSERT Into Profile (mac,image,name,age,nationality,profession,about) VALUES (0.0.0.0.0.0,/data/user/0/com.test.test/cache/scaled_image_picker3315305739073272987.jpg,test,35,test,test,test);' args []
The INSERT syntax is, in fact, wrong.
Here's your actual syntax:
INSERT Into Profile (mac,image,name,age,nationality,profession,about) VALUES (0.0.0.0.0.0,/data/user/0/com.test.fltestar/cache/scaled_image_picker3315305739073272987.jpg,test,35,test,test,test);
But the values are not expressed as TEXTs for all TEXT fields. It should be something like this:
INSERT Into Profile (mac,image,name,age,nationality,profession,about) VALUES ('0.0.0.0.0.0','/data/user/0/com.test.fltestar/cache/scaled_image_picker3315305739073272987.jpg','test',35,'test','test','test');
Also, I would suggest you use libraries like moor, that helps you a lot.

SQLite database not recognizing one of my columns

I'm trying to create an SQLite database in an Android app, but my app keeps crashing and LogCat gives the following error:
FATAL EXCEPTION: main
Process: com.zebra.leadcapture, PID: 15427
android.database.sqlite.SQLiteException: table lead_capture_database has no column named EntryNumber (code 1): , while compiling: INSERT INTO lead_capture_database(EntryNumber,BarcodeData,Notes) VALUES('0','','');
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(table lead_capture_database has no column named EntryNumber (code 1): , while compiling: INSERT INTO lead_capture_database(EntryNumber,BarcodeData,Notes) VALUES('0','','');)
Here's the code I'm using:
public void addNewEntry(String barcodeDataString, String notesString) {
leadDatabase = openOrCreateDatabase(database_name,MODE_PRIVATE,null);
String create_string = "CREATE TABLE IF NOT EXISTS " + database_name
+ "(EntryNumber TEXT,BarcodeData TEXT,Notes TEXT);";
String insert_string = "INSERT INTO " + database_name + "(EntryNumber,BarcodeData,Notes) VALUES('" + entryCount + "','" + barcodeDataString + "','" + notesString + "');";
leadDatabase.execSQL(create_string);
leadDatabase.execSQL(insert_string);
entryCount++;
}
Why is it not recognizing EntryNumber as a column?
This was answered in the comments above, but for future reference: I deleted the app from my device and reinstalled it through Android Studio which fixed the problem. I had previously been writing the app with a SQLite database without that column but with the same name. I imagine changing the string I was using for the name would have had the same effect.
You added that column after table was created. In this case, that column is not added into database. If you drop the table and recreate it, it will fix your problem without uninstalling the app. Also you can create a method for migration.

how to get AutoIncrement value to start with 1 each time table is created

I have couple of tables which will have new data every time the user logs into the application. I have a column KEY_ROWID which is autoIncrement. I want it to always start with 1.
I tried truncating the table before new data is inserted. I get an error:
"android.database.sqlite.SQLiteException: near "TRUNCATE": syntax
error (code 1): , while compiling: TRUNCATE TABLE StaffListTable"
Sugestions much appreciated.
private static final String CREATE_TABLE_STAFFLIST = "CREATE TABLE " + TABLE_STAFFLIST + " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_STAFFID + " TEXT NOT NULL, "
+ KEY_STAFFNAME + " TEXT NOT NULL);";
Its very simple, since you are truncating the table values I understand you don't have to secure them or take a back up. In such a case just dropping the table will do the trick.
In onUpdate() method, write
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE); //and call onCreate again
onCreate(db);
Let me know if you need anything else. Happy coding. :)
There's no TRUNCATE in sqlite. You can use DROP to delete tables if you really need to.
There are two ways to effect a truncate (which SQLite doesn't have). You can either DROP and then CREATE as per other answers here.
Alternatively you can do a DELETE to empty the table and then remove the entry for the table from sqlite_sequence:
DELETE FROM sqlite_sequence
WHERE name = 'table_name'
sqlite_sequence holds the last used autoincrement value for tables with such columns. Removing the row for a given table will make the autoincrement key start at 1 again.

Error inserting values in a table

I am reading values from a csv file and I am able to do that accurately. However, when I try to write those values in a systems db's table, I get an error saying one column doesn't exist in the table.
Logcat error:
E/SQLiteLog(318): (1) table hospital has no column named zip
E/SQLiteDatabase(318): Error inserting zip=36301 avgCharges=20313 avgPayment=4895 _id=10001 address=1108 ROSS CLARK CIRCLE providerName=SOUTHEAST ALABAMA MEDICAL CENTER state=AL procedure=057 - DEGENERATIVE NERVOUS SYSTEM DISORDERS W/O MCC discharges=38 city=DOTHAN
E/SQLiteDatabase(318): android.database.sqlite.SQLiteException: table hospital has no column named zip (code 1): , while compiling: INSERT INTO hospital(zip,avgCharges,avgPayment,_id,address,providerName,state,procedure,discharges,city) VALUES (?,?,?,?,?,?,?,?,?,?)
E/SQLiteDatabase(318): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
Create Table query: (all fields are in TEXT for testing)
query = "CREATE TABLE hospital(_id TEXT PRIMARY KEY, procedure TEXT, providerName TEXT, address TEXT, city TEXT, state TEXT, zip TEXT, discharges TEXT, avgCharges TEXT, avgPayment TEXT)";
db.execSQL(query);
I am sure there is no column type mismatch. It says it cannot find the column named ZIP. i do not understand whats happening here.
Query to insert values:
values.put("_id", hospital.get_id());
values.put("procedure", hospital.get_procedure());
values.put("providerName", hospital.get_providerName());
values.put("address", hospital.get_address());
values.put("city", hospital.get_city());
values.put("state", hospital.get_state());
values.put("zip", hospital.get_zip());
values.put("discharges", hospital.get_discharges());
values.put("avgCharges", hospital.get_avgCharges());
values.put("avgPayment", hospital.get_avgPayment());
db.insert(TABLE_NAME, null, values);
Any ideas on what could be done here? Thanks in advance!
The table needs to be dropped before adding a new column in the code.
You should clear the app data. Else uninstall the app and run it from Studio.
You need to implement the onUpgrade method to drop and add tables whenever the schema is changed. You can look at https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onUpgrade(android.database.sqlite.SQLiteDatabase,%20int,%20int).

INSERT OR IGNORE table with AUTOINCREMENT key in Android

I am trying to insert data to a new empty table. But I keep getting error (error code 19: constraint failed). I think the problem may caused by 'INTEGER PRIMARY KEY AUTOINCREMENT'. Here is my code:
database.execSQL("CREATE TABLE IF NOT EXISTS contacts (cid INTEGER PRIMARY KEY AUTOINCREMENT, name varchar NOT NULL, user varchar NOT NULL, UNIQUE(user) ON CONFLICT REPLACE)");
...
String sql = "INSERT OR IGNORE INTO contacts ( name , user) VALUES (?, ?)";
database.beginTransaction();
SQLiteStatement stmt = database.compileStatement(sql);
stmt.bindString(1, name);
stmt.bindString(2, entry.getUser());
int i = (int)stmt.executeInsert();
stmt.execute();
stmt.clearBindings();
stmt.close();
// error: 06-11 20:50:42.295: E/DB(12978): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
Anyone knows what wrong with the sql statement? How can I solve this problem? Thanks
I have read few articles on stackoverflow. But cannot find anyone post related to 'insert or replace' + 'INTEGER PRIMARY KEY AUTOINCREMENT'.
I think your code is doing exactly what it is supposed to be doing. Reading over your code it looks like you want it to ignore inserts where there is already something inserted. The error you are receiving is telling you that the insert has failed.
If you use INSERT IGNORE, then the row won't actually be inserted if it results in a duplicate key. But the statement won't generate an
error. It generates a warning instead. These cases include:
Inserting a duplicate key in columns with PRIMARY KEY or UNIQUE
constraints. Inserting a NULL into a column with a NOT NULL
constraint. Inserting a row to a partitioned table, but the values you
insert don't map to a partition. - "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
I would recommend catching the SQLiteConstraintException or check before inserting to see if the data is already there. If you need some ideas on how to check if data has been inserted let me know, I have had to do this before. Hope this helps.
There is a good begining to end example of SQLite on Android written by Lars Vogella here
Inside there and down a little ways here is the string that he uses for creating a table:
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";
I have not tried either his or yours just now but a few things I noticed that differ between his and yours are:
He has no space between the table name and the opening parenthesis
He has a semicolon inside of the SQL string. after the closing parenthesis.
I am not certain if those will fix it for you, but it would probably be a good start.

Categories

Resources