I am trying to figure how to insert a null value into an SQLite table in Android.
This is the table:
"create table my table (_id integer primary key autoincrement, " +
"deviceAddress text not null unique, " +
"lookUpKey text , " +
"deviceName text , " +
"contactName text , " +
"playerName text , " +
"playerPhoto blob " +
");";
I wanted to use a simple Insert command via execSQL but since one of the values is a blob I can't do it (I think).
So, I am using a standard db.Insert command.
How do I make one of the values null?
If I just skip it in the ContentValues object will it automatically put a null value in the column?
You can use ContentValues.putNull(String key) method.
Yes, you can skip the field in ContentValues and db.insert will set it NULL.
Also you can use the other way:
ContentValues cv = new ContentValues();
cv.putNull("column1");
db.insert("table1", null, cv);
this directrly sets "column1" NULL. Also you can use this way in update statement.
I think you can skip it but you can also put null, just make sure that when you first create the Database, you don't declare the column as "NOT NULL".
In your insert query string command, you can insert null for the value you want to be null. This is C# as I don't know how you set up database connections for Android, but the query would be the same, so I've given it for illustrative purposes I'm sure you could equate to your own:
SQLiteConnection conn = new SQLiteConnection(SQLiteConnString());
// where SQLiteConnString() is a function that returns this string with the path of the SQLite DB file:
// String.Format("Data Source={0};Version=3;New=False;Compress=True;", filePath);
try
{
using (SQLiteCommand cmd = conn.CreateCommand()
{
cmd.CommandText = "INSERT INTO MyTable (SomeColumn) VALUES (null)";
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// do something with ex.ToString() or ex.Message
}
Related
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.
I have an upsert method in my Android app. It query a record by id, and if it does not exist INSERT anyway UPDATE is performed.
DB can be modified quite frequently. I do not know much about SQLite locking mechanism.
Is it possible that some lock is retained on a record and so query will not return it?
If exception occurs on an INSERT operation like:
android.database.sqlite.SQLiteConstraintException: column _id is not unique (code 19)
Can I perform an UPDATE in catch clause?
I tryed REPLACE INTO, but it has no effect. Not crashes, but has no effect:
String queryString = "REPLACE INTO " + recordType + " (" + keys + ") VALUES (" + values + ")";
statement.executeUpdateDelete(); // <-- tried all 3 option: execute, executeInsert, executeUpdateDelete
You can either use insertWithConflict() and specify SqliteDatabase.CONFLICT_REPLACE, or you can wrap your logic in a transaction:
db.beginTransaction();
try {
// query for record
// if found, update; otherwise, insert
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
I have a problem to create a table. If I try to get a value from the second column, android writes a empty space in the toast. But if I try to get a value from the first column, android writes the value of the column correctly. The query functions to write the first column and to write the second column are equal. So I think the Creation of the Table is the problem. But look yourself:
public SQLiteDatabase tabelleerstellen(){
SQLiteDatabase leveldatabase = openOrCreateDatabase("leveldata.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
leveldatabase.setVersion(1);
final String CREATE_TABLE_LEVEL =
"CREATE TABLE IF NOT EXISTS tbl_level ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "ME1 TEXT, "
+ "ME2 TEXT, "
+ "ME3 TEXT, "
+ "ME4 TEXT, "
+ "ME5 TEXT, "
+ "ME6 TEXT, "
+ "ME8 TEXT, "
+ "GESCHAFFT INTEGER);";
leveldatabase.execSQL(CREATE_TABLE_LEVEL);
return leveldatabase;
}
public void tester(SQLiteDatabase leveldata){
ContentValues cursortester = new ContentValues();
cursortester.put("ME2","25");
leveldata.insert("tbl_level",null,cursortester);
String[] testerpr = {"ME2"};
Cursor testerprüfen = leveldata.query("tbl_level",testerpr,null,null, null, null,null,null);
testerprüfen.moveToFirst();
String dada = testerprüfen.getString(testerprüfen.getColumnIndex("ME2"));
Toast testertoast = Toast.makeText(getApplicationContext(),dada,Toast.LENGTH_SHORT);
testertoast.show();
}
Please check the following things:
Please make sure the table is up to date .. so try to call DROP TABLE IF EXISTS tbl_level; and recreate the table.
If you run a test make sure the table is completely empty ... so delete everything at the beggining of the test.
If the table can contain elements during the test then make sure you check the last inserted element. Please note that calling testerprüfen.moveToFirst(); moves the cursor to the first row in the table so checking that row every time is even if the table contains 50 elements is not a good thing. In this case you either use a sorting option in your query of uese while (testerprüfen != null && testerprüfen.moveToNext()) {// Your code here}
All in all I think your problem is that you already inserted more that one element in the able but you always check only the first element (with testerprüfen.moveToFirst();). Please not that there is a cursor.moveToLast() method that you can also call. This method moves the cursor to the last row in the table.
i have created a database with the table name tbl_customer and tbl_product...i can view the tbl_customer values but can't see tbl_product values.. I use adb shell to confirm my insertion. Can any one plz help me to figure out the issue
private void addProFromDB() {
// TODO Auto-generated method stub
ArrayList<String> results = new ArrayList<String>();
SQLiteDatabase sampleDB = null;
try {
list = (ListView)findViewById(android.R.id.list);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, 1, null);
sampleDB.execSQL("create table tbl_product("
+ "pro_id integer PRIMARY KEY autoincrement,"
+ "pro_name text," + "pro_price integer);");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('1','Milk','60');");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('2','Sugar','70');");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('3','Oil','200');");
Cursor c = sampleDB.query(SAMPLE_TABLE_NAMES, null, null, null, null, null,
null);
char pro_nameColumnIndex = (char) c.getColumnIndexOrThrow("pro_name");
int pro_priceColumnIndex = (int) c.getColumnIndexOrThrow("pro_price");
} finally {
if (sampleDB != null)
sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAMES);
sampleDB.close();
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, new ArrayList()));
new AddStringTask().execute();
}
Also help me how i can get its primary key and display the selected value...
Best regards....
First, it is a good idea to consider using the insert() method on SQLiteDatabase, instead of executing INSERT statements via execSQL(), particularly if you do not have much SQL experience.
Second, normally, an INSERT statement lists the columns to be inserted into, which you are not doing. SQLite might support your syntax, but it makes for more fragile code.
Third, with an autoincrement column, you do not assign your own values, as you are trying to do.
Fourth, you are putting string values into integer columns. SQLite supports that, but not by actually converting the values to integers, but rather storing the strings themselves in the columns, which may not be what you want.
Fifth, getColumnIndexOrThrow() returns an int, not a char.
Sixth, you are deleting your data from the table milliseconds after inserting it, in your finally block, assuming that SAMPLE_TABLE_NAMES is set to tbl_product. If those values are not equal, then you are inserting into and querying from a table that does not exist.
Seventh, your Cursor is dead as soon as you close() the database in your finally block.
Some combination of those probably explains "the issue".
I am attempting to make an android application with a pre-populated database. When learning about how to go about this, I came across this article http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ , which basically takes an existing sqlite database and streams it into the correct location on the android device. The data I had was dealt with in ruby, so I grabbed the sqlite gem, and created a database like so.
db = SQLite3::Database.new( "cards.db" )
db.execute("CREATE TABLE android_metadata (locale TEXT DEFAULT \"en_US\")")
db.execute("INSERT INTO android_metadata VALUES (\"en_US\")")
db.execute("
CREATE TABLE #{##card_table_name} (
_id INTEGER PRIMARY KEY,
name TEXT UNIQUE
)")
cards.each do |card|
begin
db.execute("INSERT INTO #{#card_table_name} (_id, name) VALUES (?, ?)",
card.id, card.name)
rescue => e
puts "#{card.name} (#{card.id})"
puts e
end
end
When I go into the database, both the one made from the ruby script, and the one from using adb and examining the database on the emulator, I get this for the schema.
sqlite> .schema
CREATE TABLE Cards (
_id INTEGER PRIMARY KEY,
name TEXT UNIQUE
);
However, when I pull the data back out in my application, getString can't deal with the name, specifically, this block gets into the exception clause, and prints the name successfully within that block
Cursor cursor = myDataBase.query("Cards", new String[] {"_id", "name"}, null, null, null, null, null, "5");
while (cursor.moveToNext()) {
try {
cards.add(new Card(cursor.getInt(0), new String(cursor.getString(1))));
} catch (Exception e) {
byte[] blob = cursor.getBlob(1);
String translated = new String(blob);
Log.i(MagicApp.TAG, "DB retrival blew up on " + cursor.getInt(0) + ", " + blob + " : " + translated);
e.printStackTrace();
}
}
I can deal with that, but it seems like I shouldn't have to do that. Any one else encountered this, or know what I'm doing wrong?