简体   繁体   中英

How to set a default value to a TEXT column in Sqlite?

I have a simple table. I'm trying to put a default value to a TEXT column. Here is the table query:

"CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT, book_id TEXT NOT NULL DEFAULT '0', book_name TEXT NOT NULL);"   

It creates the table but the problem occurs when i try to insert a data. I was only trying with giving a book name to book_name , as i expected that the book_id would have a default value 0 to the column. But it doesn't and it adds the null value, so the row doesn't get inserted. I have also tried with this query:

"CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT, book_id TEXT NOT NULL DEFAULT \'0\', book_name TEXT NOT NULL);"     

But the problem remains the same. I have searched the stack overflow, and got some answers but they are old and not working for me right now. So has something changed on how to set the default value to a TEXT column in sqlite. Thanks in advance :)

EDIT
Here is the insert statement:

database.insert("book", null, cv);    

Here cv is the object of ContentValues which contains only the value for the column book_name .

You can specify a default value for the column when you create the table. (It doesn't appear as though you can add a default using an ALTER statement, so you'll have to recreate your table.)

CREATE TABLE your_table_name
(MainContactName TEXT NOT NULL DEFAULT '')

For Example ,

CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT,book TEXT DEFAULT "abc");

now see that , default value is set to "abc"

Check sqllite documentation .

改变桌子,

sqlitedbInstance.execSQL("alter table myTable add column Address TEXT DEFAULT 'ABC' ");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM