Android SQLite delete() all and return value - android

This is a short snippet I found:
"Deleting data
Once data is no longer needed it can be removed from the database with
the delete() method. The delete() method expects 3 parameters, the
database name, a WHERE clause, and an argument array for the WHERE
clause. To delete all records from a table pass null for the WHERE
clause and WHERE clause argument array.
db.delete("tbl_states", "id=?", new String[] {Long.toString(countryId)});
Simply call the delete() method to remove records from the SQLite database. The delete method expects, the table name, and optionally a
where clause and where clause argument replacement arrays as
parameters. The where clause and argument replacement array work just
as with update where ? is replaced by the values in the array."
As usual I cannot find simple documentation as to:
How do I delete everything in the given table (I do not want to use .execSQL) via the .delete() method
What does it return? A cursor or interger? boolean?

Passing in null to the WHERE clause and argument array will delete everything (think if there is no WHERE clause all you are saying is delete from tbl_states).
delete returns the number of rows deleted as an integer.

This line, from your description, answers your first question:
...To delete all records from a table pass null for the WHERE clause
and WHERE clause argument array
db.delete("tbl_states", null, null);
The second answer: it returns the number of rows affected (or deleted, in integer) from the table. Say, you have 20 records in your "tbl_states" table, then, firing the above query will return 20 as integer.
int values = db.delete("tbl_states", null, null);

Related

How do I copy a column from one table to another in SQLite Android? [duplicate]

What is the exact difference between using rawquery and execSQL ??
While writing a query in android activity, when to use rawquery and when to use execSQL ?
From API documentation:
void execSQL (String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
void execSQL (String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
The documentation is inconsistent but they behave both the same. Documentation of the latter is more in depth.
Cursor rawQuery (String sql, String[] selectionArgs)
Runs the provided SQL and returns a Cursor over the result set.
Uses for rawQuery are:
You want to query the database with a SELECT statement.
=> rawQuery("SELECT ... returns a set of rows and columns in a Cursor.
It's more efficient to use DatabaseUtils.longForQuery(SQLiteDatabase, String, String[]) or DatabaseUtils.stringForQuery(...) in cases there is only a 1x1 query result, like from SELECT count(*) FROM table (which also has it's own dedicated method: DatabaseUtils.queryNumEntries(...)) - this skips creation of a Cursor object & simplifies code since there is also nothing to close, moveToNext, etc.
Special cases like PRAGMA table_info that returns data in rows (see this question)
Note: Do not use rawQuery for INSERT, UPDATE or DELETE or anything else that modifies the database. You'll run into "Why does a delete rawQuery need a moveToFirst in order to actually delete the rows?". Reason being that queries can defer reading the result until needed (= access to the cursor) which means for SQLite delaying execution of the statement.
Uses for execSQL are:
You have "instructions" for the database. Like CREATE TABLE (or any other CREATE statement, e.g. CREATE INDEX), DROP, PRAGMAs that set properties rather than returning them, ...
INSERT, UPDATE or DELETE when you're not interested in the amount of rows modified or the row id of the last insert.
When you need those, either use the update(), insert(), delete() methods or use a second statement to read those: DatabaseUtils.longForQuery with either SELECT last_insert_rowid() or SELECT changes(). Both return only 1 integer value. (see "Get updated rows count from SQLite in Android using a raw query?" and “SELECT last_insert_rowid()” returns always “0”)
Anything else that relies on executing a statement.
if you want to execute something in database without concerning its output (e.g create/alter tables), then use execSQL, but if you are expecting some results in return against your query (e.g. select records) then use rawQuery

How to break cursor processing while cursor object hold first row and move to fetch second row?

As I'm fetching only one column from SqLite database but getting more than 1MB of data in my cursor object and I can't split my database query. Is it possible to break cursor processing as soon as cursor fetches first row and at that particular time I want to hold this cursor object values in another object. After that cursor clear this value and move to next for fetching second row in database, this continues till the end of records ?
What if you do the following? (This is just an idea)
Fetch all rows you need with the id column only (fetch the id instead of the blob column).
Iterate throw that cursor and for each line fetch only one row for the given id with your blob. Then you close that Cursor and you open a new one for the next id row:
//just fetch the ids of the wanted rows
Cursor idCursor = db.query("TABLE_NAME",new String[]{"_id"}, null, null, null,null,null);
Cursor blobCursor;
//for each row (id)
while(idCursor.moveToNext())
{
//fetch one row with the blob of the given id
blobCursor = db.query("TABLE_NAME",new String[]{"image"}, "_id = ?", new String[] {new Long(idCursor.getLong(0)).toString()}, null,null,null);
if(blobCursor.moveToFirst())
{
//get the blob and store it
blobCursor.getBlob(0);
}
blobCursor.close(); //close the cursor (and release resources)
}
idCursor.close();
If you are using Cursor(SQLiteCursor) - there is no way to prevent cursor from "eating memory"(break processing as you says) after you fetched first row.
android.database.sqlite is a java wrapper for sqlite3 library which is written on C.
The fact is that sqlite3 has no function to count how much records statement will produce, so you have to scan whole resultset with help of sqlite3_step function until it returns SQLITE3_DONE. SQLiteCursor is derived from CursorWindow.
CursorWindow (has some native methods) at the moment Cursors getCount() method is called first time - it does two things : calculates count of row and caches these rows.
There is custom port(russian) of sqlite3 for android with functionality you need.
If you can not read russian:
java code
native code
native sources

Insert method of SQLiteDatabase

The second parameter of insert method of SQLiteDatabase is "nullColumnHack". WHat does this refers. What value should be passed to this parameter.
Thanks
Let's suppose you have a table named foo where all columns either allow NULL values or have defaults.
In some SQL implementations, this would be valid SQL:
`INSERT INTO `foo;
That's not valid in SQLite. You have to have at least one column specified:
INSERT INTO foo (somecol) VALUES (NULL);
Hence, in the case where you pass an empty ContentValues to insert(), Android and SQLite need some column that is safe to assign NULL to. If you have several such columns to choose from, pick one via the selection mechanism of your choice: roll of the dice, Magic 8-Ball(TM), coin flip, cubicle mate flip, etc.
Personally, I'd've just made it illegal to pass an empty ContentValues to insert(), but they didn't ask me... :-)
courtesy commonsware.
nullColumnHack 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.
Brief explanation..
nullColumnHack
optional; may be null. 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.

difference between rawquery and execSQL in android sqlite database

What is the exact difference between using rawquery and execSQL ??
While writing a query in android activity, when to use rawquery and when to use execSQL ?
From API documentation:
void execSQL (String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
void execSQL (String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
The documentation is inconsistent but they behave both the same. Documentation of the latter is more in depth.
Cursor rawQuery (String sql, String[] selectionArgs)
Runs the provided SQL and returns a Cursor over the result set.
Uses for rawQuery are:
You want to query the database with a SELECT statement.
=> rawQuery("SELECT ... returns a set of rows and columns in a Cursor.
It's more efficient to use DatabaseUtils.longForQuery(SQLiteDatabase, String, String[]) or DatabaseUtils.stringForQuery(...) in cases there is only a 1x1 query result, like from SELECT count(*) FROM table (which also has it's own dedicated method: DatabaseUtils.queryNumEntries(...)) - this skips creation of a Cursor object & simplifies code since there is also nothing to close, moveToNext, etc.
Special cases like PRAGMA table_info that returns data in rows (see this question)
Note: Do not use rawQuery for INSERT, UPDATE or DELETE or anything else that modifies the database. You'll run into "Why does a delete rawQuery need a moveToFirst in order to actually delete the rows?". Reason being that queries can defer reading the result until needed (= access to the cursor) which means for SQLite delaying execution of the statement.
Uses for execSQL are:
You have "instructions" for the database. Like CREATE TABLE (or any other CREATE statement, e.g. CREATE INDEX), DROP, PRAGMAs that set properties rather than returning them, ...
INSERT, UPDATE or DELETE when you're not interested in the amount of rows modified or the row id of the last insert.
When you need those, either use the update(), insert(), delete() methods or use a second statement to read those: DatabaseUtils.longForQuery with either SELECT last_insert_rowid() or SELECT changes(). Both return only 1 integer value. (see "Get updated rows count from SQLite in Android using a raw query?" and “SELECT last_insert_rowid()” returns always “0”)
Anything else that relies on executing a statement.
if you want to execute something in database without concerning its output (e.g create/alter tables), then use execSQL, but if you are expecting some results in return against your query (e.g. select records) then use rawQuery

Android SQLite: nullColumnHack parameter in insert/replace methods

The Android SDK has some convenience methods for manipulating data with SQLite. However both the insert and replace methods use some nullColumnHack parameter which usage I don't understand.
The documentation explains it with the following, but what if a table has multiple columns that allow NULL? I really don't get it :/
SQL doesn't allow inserting a completely empty row, so if initialValues is empty, this column [/row for replace] will explicitly be assigned a NULL value.
Let's suppose you have a table named foo where all columns either allow NULL values or have defaults.
In some SQL implementations, this would be valid SQL:
INSERT INTO foo;
That's not valid in SQLite. You have to have at least one column specified:
INSERT INTO foo (somecol) VALUES (NULL);
Hence, in the case where you pass an empty ContentValues to insert(), Android and SQLite need some column that is safe to assign NULL to. If you have several such columns to choose from, pick one via the selection mechanism of your choice: roll of the dice, Magic 8-Ball(TM), coin flip, cubicle mate flip, etc.
Personally, I'd've just made it illegal to pass an empty ContentValues to insert(), but they didn't ask me... :-)

Categories

Resources