Statement.executeInsert() Return Value - android

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.

Related

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:

What's the most efficient way to check if DB contains a specific primary key value?

I'd like to do something like this:
public boolean containsKey(int primaryKey) {
SQLiteDatabase db = getReadableDatabase();
// what should i do here to determine if the db contains the primaryKey?
}
What is the most efficient way to check if the db contains the specified value?
You could try to read the row with that PK value:
public boolean containsKey(int primaryKey) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query("TableName", null, "IDColumn = " + primaryKey,
null, null, null, null);
return cursor.moveToFirst();
}
However, it would be a better idea to use a helper function that allows you to avoid having to muck around with a cursor:
public boolean containsKey(int primaryKey) {
SQLiteDatabase db = getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, "TableName", "IDColumn = " + primaryKey) > 0;
}
You should inspect sqlite scheme. You may try
"SELECT name FROM sqlite_master WHERE type='table'"
Second variant:
PRAGMA table_info(table-name);
If You are looking for getting the column names for a table:
PRAGMA table_info(your_table_name);
Example :
PRAGMA table_info(Login);
you will get pk value 1 if you have primary key in login table.
Check this tutorial on PRAGMA
This pragma returns one row for each column in the named table.
Columns in the result set include the column name, data type, whether
or not the column can be NULL, and the default value for the column.
The "pk" column in the result set is zero for columns that are not
part of the primary key, and is the index of the column in the primary
key for columns that are part of the primary key.

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

Inserting data to SQLite table with constraint failure

Inserting data to SQLite table with constraint failure
I'm trying to insert data into SQLite table on Android. _id is primary key of the table and I am inserting a row using this method:
public void addSomeData(int id, String datetime) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, id);
contentValues.put(KEY_DATETIME, datetime);
mDb.insert(TABLE, null, contentValues);
}
The problem I get is that sometimes primary key constraint is validated and I would like to use something like INSERT IF NOT EXISTS, but preferably something that would work with ContentValues. What are my options? I understand that insertOrThrow() and insertWithOnConflict() methods only return different values, or should I use one of these methods?
Use insertWithOnConflict() with CONFLICT_IGNORE.
Will return ROWID/primary key of new or existing row, -1 on any error.
In my case "constraint failure" happened because of I had some tables which are depended on each other. As for the "insert if not exist", you can query with this id and you check if the cursor's count is bigger than zero. Check the method I'm already using in my app.
public boolean isRowExists(long rowId) {
Cursor cursor = database.query(this.tableName, this.columns, DBSQLiteHelper.COLUMN_ID + " = ? ", new String[] { "" + rowId }, null, null, null);
int numOfRows = cursor.getCount();
cursor.close();
return (numOfRows > 0) ? true : false;
}
to do so you could simply query the db to see if a row with that key exists and insert the new row only if the query returns no data.

Sqlitedatabase query not working when selecting by _id

I've been stuck on this problem with my sqlitedatabase for several days now.
My insert method works, I break after it has been run and check that the database now contain rows (before it was empty), by querying for the entire database, which works.
This is the insert method which returns the generated puzzleId.
public int savePuzzleToEdit(ContentValues puzzle, Integer puzzleId) {
Integer id = puzzle.getAsInteger(General.ID);
if (id == 0 && puzzleId == null) {
puzzle.remove(General.ID);
puzzleId = (int) ourDatabase.insert(PUZZLE_TABLE, null, puzzle);
}else {
....
}
return puzzleId
The query method however, does not return any results, aka the cursor is empty.
public ArrayList<ContentValues> getCreatedPuzzles(int puzzleId) {
Cursor c = ourDatabase.query(PUZZLE_TABLE, null, "_id = " + puzzleId, null, null, null, null, null);
while (c.moveToNext()) { // Generate return list ...}
I have tried breaking after the insert and before the query in order to see if there is indeed rows in the database, which there is. I am however not able to query by selecting by id. I can however, query by the other fields in the table and get the correct rows as a result, so it has to be the _id field which has an error.
I have also tried to use the rawQuery method which also works when querying for the entire database or by any of the other fields but id.
This is the create statement:
private static final String PUZZLE_TABLE_CREATE =
"CREATE TABLE puzzle ( _id INTEGER, name varchar(45), category " +
"varchar(25), publishdate DATE, rating INT, timesplayed INT, numberOfQuestions INT);";
As I understood it the id has to be INTEGER in order to auto_increment on insert, which I believe works since the insert method returns a id, which varies from one insert to another.
The query method does not return any errors or exceptions, and it just seems like there are no rows in the table with that id. I have assumed that the returned puzzleId is also being stored as the id in the table, but that might be wrong?!
Any and I mean any suggestions or insights on how to try to fix this problem is highly appreciated.
first thing first your create table statement might be wrong the _id will not autoincrement if you don't mention it in the statement. it should be like this
_id integer primary key autoincrement
and also check your create table statement for other errors

Categories

Resources