Unable to insert 'NULL' as text in SQLIte - android

I am trying to insert text 'NULL' in SQLite table and getting syntax error near :'NULL'.
Below is my SQL insert statement.
db.execSQL("INSERT INTO POINTS_TABLE VALUES('NULL','NULL','NULL')");

I think you need to change your code from
db.execSQL("INSERT INTO POINTS_TABLE VALUES('NULL','NULL','NULL')");
to
db.execSQL("INSERT INTO POINTS_TABLE (COL1,COL2,Col3) VALUES ('NULL','NULL','NULL');");
further to this I think you want to loose the quotation marks unless you want to store the string "NULL" in these columns. if your data types for these columns are not strings then this will throw an error.

Related

how to store syntax in sqlite

1.which data type should be used to store data like group=AB+ ?
E/SQLiteLog: (1) near "group": syntax error SQLiteDatabase:
Error inserting
district=jhapa phone=9843284985 name=Tom group=AB+
My table is in this format
CREATE TABLE IF NOT EXISTS `Doners` (\n" +
"\t`name`\tTEXT,\n" +
"\t`phone`\tNUMERIC,\n" +
"\t`group`\tBLOB,\n" +
"\t`district`\tTEXT\n" +
");";
For Android you can either use
- native SQL via the SQLiteDatabase execSQL method
- the SQLiteDatabase convenience insert family of methods :-
insert (effectively INSERT OR IGNORE)
insertOrThrow (standard INSERT)
insertWithOnConflict
SQLiteDatabase - insert
So assuming that you want to insert :-
Tom into the name column,
9843284985 into the phone column,
AB+ into the group column,
NOTE that group is an SQLite keyword and therefore cannot be used and will result in a syntax error, unless it is enclosed SQL As Understood By SQLite - SQLite Keywords
jhapa
And that the variable db is an instantiated instance of the SQliteDatabase class then :-
you could use :-
db.execSQl("INSERT INTO `Doners` VALUES('Tom',9843284985,'AB+','jhapa')");
noting that a value must be provided for all the defined columns and that the values should be in the order that the columns were defined in.
or you could use :-
db.execSQL("INSERT INTO Doners (district,phone,name,`group`) VALUES ('jhapa','9843284985','Tom','AB+')");
Here you specify the columns into which the values will be placed, you can specify them in what order you like (values will be inserted according to the order), you can also omit columns (dependant upon the column definition)
Defining a column as NOT NULL would require a column and value. However, if a DEFAULT value has been defined as well as NOT NULL then the column can be omitted.
you could use the insert convenience method like :-
ContentValues cv = new ContentValues();
cv.put("phone","9843284985");
cv.put("name","Tom);
cv.put("`group`","AB+");
cv.put("district","jhapa");
long rowid = db.insert("Doners",null,cv);
rowid will be the rowid of the inserted row (a unique identifier of the row) or if no row was inserted then -1.
the convenience method :-
it builds the SQL on your behalf
protects against SQL injection
encloses values accordingly
suitable encodes byte[]'s into the the x'ff00fe.......' used by SQL.
returns the rowid (executes a query using last_insert_rowid()).
in regards to :-
which data type should be used to store data like group=AB+ ?
Due to SQLite's flexibility it probably does not matter what type is assigned to the column. That is with the exception of the rowid or an alias of the rowid (the_column INTEGER PRIMARY KEY makes the_column an alias of the rowid column) any type of data can be stored in any type of column and to further expand on the flexibility type can be virtually anything (keywords and other syntactically confusing values excepted).
As such CREATE TABLE mytable (mycolumn RUMPLESTILTSKIN) is valid (column has numeric affinity). see - Datatypes In SQLite Version 3

Finding tables having columntype BLOB in sqlite

How can I find the tables having column Blob type in Sqlite. I need to get the table names from which I get the column blob type and then want to see the total no. of records where the blob is not empty.
If you wanted tables that have a column defined as a blob then you could use
SELECT * FROM sqlite_master WHERE sql LIKE '%blob%';
as the basis for determining the tables. e.g. this could return results such as :-
However, this does not necessarily find all values that are stored as blobs. This is because with the exception of the rowid column or an alias thereof, any type of value (blob included) can be stored in any column.
e.g. consider the following :-
DROP TABLE IF EXISTS not_a_blob_table;
CREATE TABLE IF NOT EXISTS not_a_blob_table (col1 TEXT, col2 INTEGER, col3 REAL, col4 something_or_other);
INSERT INTO not_a_blob_table VALUES
('test text',123,123.4567,'anything'), -- Insert using types as defined
(x'00',x'12',x'34',x'1234567890abcdefff00') -- Insert with all columns as blobs
;
SELECT typeof(col1),typeof(col2),typeof(col3),typeof(col4) FROM not_a_blob_table;
This results in :-
If you want to find all blobs then you would need to process all columns from all rows of all tables based upon a check for the column type. This could perhaps be based upon :-
SELECT typeof(col1),typeof(col2),typeof(col3),typeof(col4),* FROM not_a_blob_table
WHERE typeof(col1) = 'blob' OR typeof(col2) = 'blob' OR typeof(col3) = 'blob' OR typeof(col4) = 'blob';
Using the table above this would result (only the 2nd row has blobs) in :-
A further complication is what you mean by not empty, null obviously. However what about x'00'? or if you used a default of zeroblob(0) ?.
zeroblob(N)
The zeroblob(N) function returns a BLOB consisting of N bytes of 0x00. SQLite manages these zeroblobs very efficiently. Zeroblobs can
be used to reserve space for a BLOB that is later written using
incremental BLOB I/O. This SQL function is implemented using the
sqlite3_result_zeroblob() routine from the C/C++ interface.
If null though then this wouldn't have a type of blob, instead it's type would be null, which could complicate matters if checking for all values stored as blobs.
You may wish to consider having a look at the code from Are there any methods that assist with resolving common SQLite issues?
as this could well be the basis for what you want.
You also wish to have a look at typeof(X) and zeroblob(N).

Insert statement in sqlite android with db.ececSQL statement

I just want to insert values into a table if the value provided does not exists in that table, I mean I have provided a column as UNIQUE, so sqlite3 UNIQUE constraint will be broken when that value is tried to input twice, i want an sqlite3 insert statement which helps to do this my code is. I read that INSERT IGNORE is used for this purpose. Can somebody provide me with syntax to do this correctly?
My code is given below.
String insertQuery1 = "INSERT INTO Bookdetails bookpath,lastchapter VALUES(?,?)";
db.execSQL(Query1, new String[] { filepath, none });
What is the correct syntax for this query? filepath and none are string which have values assigned
Also this table Bookdetails has a primarykey field 'id' which is auto increment? will it create any problems when data is inserted like this way?
String insertQuery1 = "INSERT INTO Bookdetails (bookpath,lastchapter) VALUES(?,?)";
db.execSQL(Query1, new String[] { filepath, none });
Change
INSERT INTO Bookdetails bookpath,lastchapter VALUES(?,?)
to
INSERT OR IGNORE INTO Bookdetails (bookpath,lastchapter) VALUES(?,?)
The OR IGNORE causes that when a constraint such as UNIQUE is violated, the insert doesn't take place and there won't be an error.
The column names to insert to need to be in () parens.
Additionally, you're passing some other query to execSQL() than the insertQuery1 here.
Also this table Bookdetails has a primarykey field 'id' which is auto increment? will it create any problems when data is inserted like this way?
No, since no insertion takes place.
If you had INSERT OR REPLACE instead of the ignore, it would translate to a DELETE followed by INSERT, generating a new row id in case the id was not specified in the insert itself.
The query is wrong:
INSERT INTO Bookdetails bookpath,lastchapter VALUES(?,?)
It should be:
INSERT INTO Bookdetails (bookpath, lastchapter) VALUES (?, ?)
Mind the parentheses surrounding the fields list!

Error inserting values in a table

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).

SQLite prevents duplicate column names in my VIEW

I am creating a SQLite VIEW that is the result of multiple joined tables. All my tables have an _id column as required by Android. The result has multiple columns with the same _id name, but SQLite adds ":1" and ":2" to the duplicate names so they are no longer duplicates.
If you run the below SQL you can see the resulting view has interesting column names:
CREATE TABLE things ("_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , "name" TEXT NOT NULL);
CREATE TABLE thing_colors ("_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , "thing_id" INTEGER NOT NULL , "color" TEXT NOT NULL);
INSERT INTO things VALUES ("1","car");
INSERT INTO things VALUES ("2","horse");
INSERT INTO things VALUES ("3","lamp");
INSERT INTO thing_colors VALUES ("1","1","blue");
INSERT INTO thing_colors VALUES ("2","1","red");
INSERT INTO thing_colors VALUES ("3","2","brown");
INSERT INTO thing_colors VALUES ("4","3","silver");
INSERT INTO thing_colors VALUES ("5","3","gold");
CREATE VIEW things_and_colors AS SELECT * FROM things JOIN thing_colors ON things._id=thing_colors.thing_id;
SELECT * FROM things_and_colors;
I find these renamed column names useful but is this normal SQL behavior and is it fine for me to rely on it?
But of course this is just an example, in real life I am joining three tables and the result has about 70 columns in it, of which 3 are named _id.
Don't select star, select the columns individually and assign an alias as needed.
No, you can't depend on the view renaming your columns to avoid conflicts. I don't have a copy of the standard handy so I can't quote chapter and verse but I know that PostgreSQL will say this:
ERROR: column "_id" specified more than once
and MySQL will say this:
ERROR 1060 (42S21): Duplicate column name '_id'
Those are the only databases I have handy at the moment.

Categories

Resources