我想知道如何在Android中的SQLite表中插入一个空值。
这是表:
"create table my table (_id integer primary key autoincrement, " +
"deviceAddress text not null unique, " +
"lookUpKey text , " +
"deviceName text , " +
"contactName text , " +
"playerName text , " +
"playerPhoto blob " +
");";
我想通过execSQL
使用一个简单的Insert命令,但由于其中一个值是blob,我无法做到(我认为)。
所以,我使用标准的db.Insert
命令。如何使其中一个值为null?
如果我只是在ContentValues
对象中跳过它,它会自动在列中放置一个空值吗?
是的,您可以跳过ContentValues中的字段,db.insert会将其设置为NULL。你也可以用另一种方式:
ContentValues cv = new ContentValues();
cv.putNull("column1");
db.insert("table1", null, cv);
这个directrly将“column1”设置为NULL。您也可以在update语句中使用这种方式。
我认为你可以跳过它,但你也可以把null,只要确保在你第一次创建数据库时,你不要将列声明为“NOT NULL”。
在insert query string命令中,可以为要为null的值插入null
。这是C#,因为我不知道你是如何为Android设置数据库连接的,但是查询是一样的,所以为了说明的目的我给出了它,我相信你可以等同于你自己:
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
}