Android SQLITE query exception error? - android

I want to add sqlite in my application i have created DB and table but the SELECT and INSERT query is not working i Don't know why?
Here i have added my code:
static Cursor c;
SQLiteDatabase db;
db=openOrCreateDatabase("weatherregisterDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS weatherRegister(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR,username VARCHAR,password VARCHAR,confirmpassword VARCHAR);");
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
db.execSQL("INSERT INTO weatherRegister(id,name,username,password,confirmpassword) VALUES('',sample,sample,sample,sample);");
c=db.rawQuery("SELECT username FROM weatherRegister WHERE username=sample", null);
My Error is:
android.database.sqlite.SQLiteException: no such column: sample (code 1): , while compiling: INSERT INTO weatherRegister(id,name,username,password,confirmpassword) VALUES('',sample,sample,sample,sample);

could you provide the error ?
but at first look this line
db.execSQL("INSERT INTO weatherRegister(id,name,username,password,confirmpassword) VALUES('',sample,sample,sample,sample);");
should be :
db.execSQL("INSERT INTO weatherRegister(id,name,username,password,confirmpassword) VALUES('sample','sample','sample','sample');");
you don't have to wire ('') for (id) if it's auto increment , also (String) values should be between ('')
and the same for the select query
Original :
SELECT username FROM weatherRegister WHERE username=sample
Update to :
SELECT username FROM weatherRegister WHERE username='sample'
hope that will help before you show us the error.

Ahmad Okaily's answer is correct. One more thing is you don't need to write _id in your insert statement since it's auto-increment.
I've tried it in SQLite command line and seems it's working fine.
Can't give you an Android code version because my PC in company is too slow for eclipse or android studio.
SQLite version 3.8.7.4 2014-12-09 01:34:36
Enter ".help" for usage hints.
sqlite> INSERT INTO weatherRegister(id,name,username,password,confirmpassword) VALUES('sample','sample','sample','sample');
Error: 4 values for 5 columns
sqlite> INSERT INTO weatherRegister(name,username,password,confirmpassword) VALUES('sample','sample','sample','sample');
sqlite> select * from weatherRegister;
1|sample|sample|sample|sample
sqlite>

Try changing this line
c=db.rawQuery("SELECT username FROM weatherRegister WHERE username=sample", null);
to
c=db.rawQuery("SELECT username FROM weatherRegister WHERE username='sample'", null);
Please note single inverted comma near "sample".Hope it will help.Thanks.

Instead of using the VARCHAR data type use TEXT as the datatype for your attributes.

Related

SQLCipher join two database tables

I successfully attached DB to another DB using SQLCipher like this:
ATTACH DATABASE '/storage/emulated/0/Android/data/testApp/files/dbTest1.s3db'
AS dbTest1 KEY 'Password';
I am not getting any error. When I try to use this query:
SELECT column1, column2, column3 FROM dbTest1.SaTTest
UNION SELECT column1,column2,column3 FROM SatTest
WHERE (Address1 LIKE '%cor%' OR column1 LIKE '%cor%')
I am getting this error:
I/Database(2587): sqlite returned:
error code = 1, msg = no such table: dbTest1.SaTTest.
How can i use alias in attached database tables?
I believe it's just a typo, it should be dbTest1.SatTest instead of dbTest1.SaTTest. Please always keep in mind case-sensivity

Android SQLite Beginner Error

Just a real quick question, probably something really simple but I've never done ANYTHING with databases before, can someone tell me why the second line is giving me an error?
Thank you! :)
SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS index (ChalNum INT(3));");
ERROR:
ERROR: 02-12 05:21:47.573: E/AndroidRuntime(1199): java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.example/com.example.Home}:
android.database.sqlite.SQLiteException: near "Index": syntax error (code 1): ,
while compiling: CREATE TABLE IF NOT EXISTS Index (ChalNum INT(3));
You can not use the Index name for the Table. Its a keyword for SQLite.
Try out with Index1 or some other name.
Besides using exact word Index use Index1 as below:
db.execSQL("CREATE TABLE IF NOT EXISTS Index1 (ChalNum INT(3));");
INDEX is a SQLite keyword. Choose a different name for your table.
You will like to use:
db.execSQL("CREATE TABLE IF NOT EXISTS index1 (ChalNum INTEGER);");
Emil

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).

Error: No such column name

I have been trying to execute a query:-
String selectQuery="SELECT "+ROLE+" FROM "+TABLE_EMPLOYEE+ " WHERE "+USER_ID+ "='"+userId+"' AND "+PASSWORD+"='"+password+"';";
cursorObj = dbObj.rawQuery(selectQuery, null);
This will result to:-
SELECT Role FROM employee WHERE User_Id='HondaSE' AND Password='456';
The logcat says:-
01-08 12:05:10.070: W/System.err(9318): android.database.sqlite.SQLiteException: no such column:
HondaQE: , while compiling: SELECT Role FROM employee WHERE User_Id=HondaQE AND Password=123;
I have tried to run the query with double quotes as well, for userId and password. resulting in:-
SELECT Role FROM employee WHERE User_Id="HondaSE" AND Password="456";
However both the queryies work perfectly fine when executed in SQLITE Data browser.
Both respond with same error.
Your logcat shows as below.
while compiling: SELECT Role FROM employee WHERE User_Id=HondaQE AND Password=123;
there is no single quotes around strings in User_Id=HondaQE AND Password=123.
You weren't compiling your raw query correctly. I would advise you to use "query" instead and use selection args to avoid these mistakes and possible sql injections.
Rewrite like this
String selectQuery="SELECT "+ROLE+" FROM TABLE_EMPLOYEE " WHERE USER_ID ='" + userId + "' AND PASSWORD = '" +password+ "'";
I had the closed the db before accessing the cursor. This was the error.
After accessing the cursor, the db is to be closed. Error solved.

Android Sqlite INSERT error when table contains only _id

I have a SQLite table that contains only the _id:
"create table rule (_id integer primary key);";
When running this set of commands:
ContentValues initialValues = new ContentValues();
mDb.insert(TABLE, null, initialValues)
I obtain the following exception:
android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO rule(null) VALUES (NULL)
The initial error occurs because ContentValues cannot be empty. Android provides a convenience parameter called nullColumnHack that allows you to pass a single column with the value null, to bypass this problem.
However this doesn't apply in my case because the row id (_id) cannot be null! Based on the syntax found in the SQLite language docs, I would like to be able to run the SQLite code:
INSERT INTO rule DEFAULT VALUES;
How can i achieve something like this using the android insert method? Or is there something I need to add to my create statement?
UPDATE: In the situation where a table contains ONLY a rowid, the proper syntax is to use INSERT INTO __ DEFAULT VALUES.
The sqlite insert method listed in android does not support DEFAULT VALUES as an option.
A bug has been filed with google and to get support for default values the following commands would need to be executed:
mDb.execSQL("INSERT INTO rule DEFAULT VALUES;");
Cursor c = mDb.rawQuery("SELECT last_insert_rowid()",null);
c.moveToFirst();
int rowid = c.getInt(0);
As stated in the accepted answer, we can get around this (and DEFAULT VALUES) by using nullHackColumn and assigning the row id (_id) to null and letting SQLite make the conversion from null to the auto-incremented value.
As jeet mentioned you can provide nullColumnHack as a second parameter. And as you yourself mentioned autoincrement isn't necessary to increment a value of primary key.
So the syntax:
insert into rule (_id) values(null)
where _id is primary key and autoincremented value is correct for sql. I think most SQL databases will replace null with new incremented value, at least MySQL, SQLite and Oracle can do this
Thus:
ContentValues cv = new ContentValues();
db.insert("rule", "_id", cv);
should give you desired results.
You need to add autoincrement to your create table query like:
"create table rule (_id integer primary key autoincrement);";
In your case you need to manually set the ID of the row with each insert. this way it will increment it automatically when you insert an empty row as you did in your case.
Try this way :
ContentValues initialValues= new ContentValues();
if(check here --id is null----)
{
initialValues.put("_id", "0");
}
else
{
initialValues.put("_id", id);
}
mDb.insert(TABLE, null, initialValues)
Check following:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String, java.lang.String, android.content.ContentValues)
SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided values is empty, no column names are known and an empty row can't be inserted. If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values is empty.
the insert needs a null value you just have to put
db.insert ("people", null, c);

Categories

Resources