Insert null in Sqlite table

后端 未结 4 603
逝去的感伤
逝去的感伤 2020-12-29 20:51

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         


        
相关标签:
4条回答
  • 2020-12-29 20:56

    You can use ContentValues.putNull(String key) method.

    0 讨论(0)
  • 2020-12-29 21:00

    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.

    0 讨论(0)
  • 2020-12-29 21:03

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

    0 讨论(0)
  • 2020-12-29 21:07

    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
    }
    
    0 讨论(0)
提交回复
热议问题