How insert from table A to Table B in sqlite? - android

i want insert from table A to table B
My code:
String sql = "Insert Into B (emsunitcode,gpsacquisition_datetime,insert_datetime) "
+ "Select emsunitcode,gpsacquisition_datetime,update_datetime From A";
database.rawQuery(sql, null);
But it not work.
How insert from table A to Table B in sqlite?

Use execSQL() and not rawQuery().
rawQuery() just compiles the SQL but doesn't run it. execSQL() both compiles and runs.

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.

Can you set a column equal to another column in a table using SQLiteDatabse update()?

I need to make a column equal to another column in the table. I can't figure it out using the update method of my SQLiteDatabase.
I know the SQL statement is:
UPDATE coolTable SET columnA = columnB;
Do I put it in the ContentValues I pass the function? or the selection string?
You can use update() only to set literal values (as bind params), not any other kind of expression supported by sqlite SQL syntax.
Use execSQL() to execute your raw UPDATE query with column name expression.
execSQL() with error checking:
SQLiteDatabase db = getReadableDatabase();
try {
long count = DatabaseUtils.queryNumEntries(db, "pweb");
db.execSQL("update pweb set h_id = _id;");
long rows = DatabaseUtils.longForQuery(db, "SELECT changes()", null);
if(count != rows ) Log.e("wrong count","update failed");
}
catch(SQLException e){
Log.e("SQLException","update failed");
}
db.close();
but I was wondering if it is possible to use the database's update()
function instead of execSQL()
You can use sqlite3 to view and manipulate you data, and test out sql commands.
Create a table:
CREATE TABLE pweb (_id INTEGER PRIMARY KEY,h_id INTEGER ,sent INTEGER);
See the original rows:
sqlite> select * from pweb;
1|10|1
2|20|1
3|30|0
4|40|0
execute a column update:
sqlite> update pweb set h_id = _id;
See the changes to all rows:
sqlite> select * from pweb;
1|1|1
2|2|1
3|3|0
4|4|0
Something more complex ?
sqlite> update pweb set h_id = _id + 1;
result:
sqlite> select * from pweb;
1|2|1
2|3|1
3|4|0
4|5|0
See also Understanding SQLITE DataBase in Android:

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();

SQlite AUTOINCREMENT with Statement Binding

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();

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