SQlite AUTOINCREMENT with Statement Binding - android

Created a table
"CREATE TABLE student ( id INTEGER PRIMARY KEY AUTOINCREMENT, name
TEXT, course TEXT)"
Now when trying to insert a row like
String sql = "INSERT INTO student" +" VALUES (?,?)";
SQLiteStatement statement = myWriteableDatabase.compileStatement(sql);
statement.clearBindings();
statement.bindString(2, "Some Name");
statement.bindString(3, "Some Course");
statement.execute();
this throws an exception saying
table student has 3 columns but 2 values were supplied: , while compiling: INSERT INTO student VALUES (?,?);
Why is this exception even though I have made id column as AUTOINCREMENT.

The PRIMARY KEY autogeneration only kicks in if a NULL is inserted into the column.
Either specify the columns you want to insert to:
INSERT INTO student(name,course) VALUES ...
so that the id column gets a NULL default value, or explicitly insert a NULL value, for example
INSERT INTO student VALUES(NULL,?,?)
Also check your bind indices. They are not correct - it's the index of the ? in the query string, not the index of the column in the table.

First you have an error in yours bindString calls, you only have 2 ? signs in your query, the first make reference to the name column and the second ? make reference to the course column.
If you want use the query like this:
INSERT INTO student VALUES ('name', 'course')
you need change your code to (see the query):
String sql = "INSERT INTO student" +" VALUES (NULL, ?,?)";
SQLiteStatement statement = myWriteableDatabase.compileStatement(sql);
statement.clearBindings();
statement.bindString(1, "Some Name");
statement.bindString(2, "Some Course");
statement.execute();
Or you can use this query:
INSERT INTO student (name, course) VALUES ('first', 'second')
In this case you can use this code:
String sql = "INSERT INTO student (name, course)" +" VALUES (?,?)";
SQLiteStatement statement = myWriteableDatabase.compileStatement(sql);
statement.clearBindings();
statement.bindString(1, "Some Name");
statement.bindString(2, "Some Course");
statement.execute();

Related

Statement.executeInsert() Return Value

Say I have ProductVersion Table:
CREATE TABLE ProductVersion
(
Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
PrvVersionName NOT NULL
);
And I have this code to do INSERT on this table:
SQLiteDatabase database = this.getWritableDatabase();
String sql = "INSERT INTO ProductVersion (PrvVersionName) VALUES (?);";
SQLiteStatement s = database.compileStatement(sql);
s.bindString(1, data.getVersionName());
long id = s.executeInsert();
s.close();
My question, is the value returned from s.executeInsert() same as if I query using "SELECT last_insert_rowid();" after doing this INSERT?
executeInsert() will return the ID of the row inserted
FROM DOCS
SQLiteStatement.executeInsert ()
Execute this SQL statement and return the ID of the row inserted due to this call. The SQL statement should be an INSERT for this to be a useful call.
The documentation for SQLiteStatement#executeInsert seems to confirm this:
Execute this SQL statement and return the ID of the row inserted due to this call. The SQL statement should be an INSERT for this to be a useful call.

How to properly format queries while inserting Commas to Separate Strings in SQLITE

I need to insert coordinates in SQLLIte Table in Android
My Query is as below .
Its gives a Syntax error due to cordinates which contain string by comma separated information .
INSERT INTO "tableNonOilFarmer" ("farmerId","FirstName","MiddleName","LastName","FatherName","DOB","CategoryId","MobileNo","LandlineNo","StateId","DistrictId","TalukaMandalId","ClusterId","VillageId","Pincode","RsNumber","Area","LocationId","BorewellAvailable","BorewellDepth","SoilType","Flood","CurrentCropId","CurrentCropStatusId","CurrentCropAge","CurrentCropRating","Awareness","Interested","ContactDate","NextCrop","OverallRating","CreatedOn","Latitude","Longitude","Coordinates","Converted","Status","StatusBy","StatusDate","Comments","UserId","Sync") VALUES (3,test,test,test,test,2017-12-27,6,64,58,1,01,02,01,04,96559,1,1,1,false,353,kdf,1,1,1,5555,3,true,true,2017-12-27,,5,2017-12-27,16.868542,81.306554,81.30682,16.8682,0 81.306309,16.86842,0 81.306607,16.869098,0 81.307039,16.868813,0 81.30682,16.8682,0,false,0,null,1,null,167,S)
You can Use PreparedStatement for inserting the Data with commas
SQLiteDatabase db = dbHelper.getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("INSERT INTO tableNonOilFarmer (FirstName,Adress) VALUES (?,?)");
stmt.bindString(1, "First");
stmt.bindString(2, "No 1, 1st street, MyCity");
stmt.execute();

New Column added to a table doesnt show up in query

I am adding a new column to an existing table and adding a new entry to the table with valid data present only in new column (other column being 0 by default)
Adding Column :
final String DB_ADD_COLUMN_STATEMENT_TABLE_SHOP_NAME =
"ALTER TABLE "+ shopName + " ADD COLUMN "+ "D" + time + " FLOAT";
try {
mDB.beginTransaction();
//SQLiteStatement statement = mDB.compileStatement(DB_ADD_COLUMN_STATEMENT_TABLE_SHOP_NAME);
//statement.execute();
mDB.execSQL(DB_ADD_COLUMN_STATEMENT_TABLE_SHOP_NAME);
mDB.setTransactionSuccessful();
}
catch (Exception e) {
Log.d(LOG_TAG,"addItemSample : Exception while adding column to table!!");
}
finally {
mDB.endTransaction();
}
Adding a new entry to the table with data only in this column succeeds.
But when I query the table , this new column doesn't show up in the cursor.
Though the adding column and querying happen in different threads, they are serialized from the way they are being called from my code (ie first column is added and then db is queried) and also the I am using a single connection to db.
I wondering what might be reason for this?
PS:When db query is performed immediately after inserting the column , it shows up.
depends on your query statement.
is it like
String query="select id, column1, column 2 from "+shopName+" where yourcondition";
?
may be you have to add column?
String query="select id, column1, column2, D192200 from "+shopName+"";
or you may query all columns
String query="select * from "+shopName+"";
The issue could be that you are adding a column that expects NOT NULL values
Try something like this:
ALTER TABLE "+ shopName + " ADD COLUMN "+ "D" + time + " FLOAT" default 0 NOT NULL;
Use which ever default value you need and update the values as needed.

SQLite bind insert statement throwing error with unique key

I'm using the following code to do an insert into the database using a batch insert for android SQLite
String sql = "INSERT INTO "+ SQL_DATABASE_GLOBALS.TEMPSORT_TABLE +" VALUES (?,?,?,?,?,?,?,?,?,?,?);";
Log.d("Line", "1");
SQLiteStatement statement = SQL_DATABASE_GLOBALS.SQL_DATABASE.compileStatement(sql);
Log.d("Line", "2");
SQL_DATABASE_GLOBALS.SQL_DATABASE.beginTransaction();
Log.d("Line", "3");
statement.clearBindings();
statement.bindLong(1, 0);
statement.bindString(2, "Site");
statement.bindString(3, this.SearchLocation);
statement.bindString(4, TitleElement);
statement.bindString(5, NewURL);
statement.bindString(6, ImageHREFElement);
statement.bindString(7, PriceElement);
statement.bindString(8, "WebSIteDescription"); //Description
statement.bindString(9, LocationElement);
statement.bindString(10, TrueDateTime);
statement.bindString(11, TrueDateTime);
Log.d("Line", "4");
long result = statement.executeInsert();
Log.d("Results", "SQL Result" + result);
SQL_DATABASE_GLOBALS.SQL_DATABASE.setTransactionSuccessful();
SQL_DATABASE_GLOBALS.SQL_DATABASE.endTransaction();
Now the insert itself works works but the problem i'm having is the 1st item in the database is actually a unique auto increment column. So i'm getting the error...
"Primary Key must be Unique"
How would I deal with this normally? do i really have to sit and create the actual insert statement itself fully instead of just using the the method I did?
No I don't want to use constructed values either, i'm wanting to stick with this type of insert.
You're binding the value 0 to the unique column. To make the autoincrement mechanism kick in, bind a null there.
Change
statement.bindLong(1, 0);
to
statement.bindNull(1);

SQLite and Android Insert/Updates on SQLiteDatabase -CompiledStatements-

Pretend I have a table with 2 columns. _id and name. _id is the primary key and I do not want to set this value manually. I want to perform an insert of name="john," and let the program create my own _id. I am unclear what "index" to use when inserting and how many question marks to use. Does this code do the job? Should the index for john be 1 or 2?
String TABLENAME = "table";
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(?);");
statement.bindString(1,"john");
statement.executeInsert();
Next, say I want to manually set my own _id value. Would I change the code to:
String TABLENAME = "table";
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(?,?);");
statement.bindLong(1,666); //Manual _id.
statement.bindString(2,"john");
statement.executeInsert();
Your first example where you provide only the name will not work:
sqlite> create table test (i integer primary key autoincrement, j text);
sqlite> insert into test values ('asd');
Error: table test has 2 columns but 1 values were supplied
sqlite> insert into test values (null, 'asd');
sqlite> select * from test;
1|asd
sqlite> insert into test (j) values ('asd');
sqlite> select * from test;
1|asd
2|asd
so you need to identify the name column as the destination of the sole value this way, (or as you mentioned in your comment pass null):
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" (name) VALUES(?);");
Your second example should work fine.
This would apply to some table created this way:
create table SomeTable (_id integer primary key autoincrement, name text)
Then
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(null,?);");
statement.bindString(1,"john");
Should also work.

Categories

Resources