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
Related
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.
I have a table in an SQLite database on Android that only contains a column with the row ID. This table is used to link datasets in different tables. When I try to insert a new row in the table it throws this exception:
android.database.sqlite.SQLiteException: near "null": syntax error
(code 1): , while compiling: INSERT INTO journeyDetailsTable(null)
VALUES (NULL)
My table is created like this:
private static final String CREATE_TABLE_JOURNEY_DETAIL = "create table " +
TABLE_NAME + " (" + ID_COLUMN + " integer primary key autoincrement);";
And I am trying to insert a new row like this:
parentID = db.insert(ANOTHER_TABLE, null, new ContentValues());
Any ideas?
The docs for SQLiteDatabase.insert(String, String, ContentValues) clearly state that SQL doesn't allow inserting a completely empty row without naming at least one column name. This means that if you do not specify any values, you need to specify a column name in which to insert the NULL into. You should be fine with db.insert(ANOTHER_TABLE, ID_COLUMN, new ContentValues()) to accomplish that.
Regardless, you should probably re-think your database structure as having tables set up like this does not seem effective, maintainable and overseeable, especially in the long run.
Just pass ID_COLUMN as column name in your insert, null isn't a column, but passing null to id will let ID be auto-incremented:
INSERT INTO journeyDetailsTable(ID_COLUMN) VALUES (NULL)
demo
In my project I used OrmLite to create a table named OrderItem, in logcat it create table successfully but when I try to insert a record it show an exception. I would like to know why this is happening? Please my logcat.
Thanks
After create OrderItem
09-12 07:30:13.075: I/TableUtils(22428): creating table 'OrderItem'
09-12 07:30:13.085: I/TableUtils(22428): executed create table statement changed 1 rows: CREATE TABLE `OrderItem` (`custom_taste` VARCHAR , `order_id` INTEGER , `name` VARCHAR , `id` INTEGER PRIMARY KEY AUTOINCREMENT , `food_id` INTEGER , `quantity` INTEGER )
After insert a record to OrderItem it show food_id column not found. In above logcat food_id column is created.
09-12 07:32:00.885: E/SQLiteLog(22428): (1) table OrderItem has no column named food_id
09-12 07:32:00.905: W/System.err(22428): java.sql.SQLException: Unable to run insert stmt on object com.expresspos.mm.object.OrderItem#40ddbdd8: INSERT INTO `OrderItem` (`custom_taste` ,`order_id` ,`name` ,`food_id` ,`quantity` ) VALUES (?,?,?,?,?)
While I am waiting for somebody's answer, I searched some solution to my qestion. This link is helpful https://groups.google.com/forum/#!topic/ormlite-android/k-i1MnaL-aQ.
Here is my solution,
// some set of alter table statements to tweak the schema
orderItemDao.executeRaw("ALTER TABLE `OrderItem` ADD COLUMN food_id INTEGER DEFAULT 0;");
I didn't think about that I need to alter OrderItem table when adding a column. I have to alter table because that database I have preferred is already been created.
Thanks
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).
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.