简体   繁体   English

如何在Sqlite中为TEXT列设置默认值?

[英]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. 我正在尝试将默认值放入TEXT列。 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. 我只是尝试给book_name一个书名,因为我预计book_id的列默认值为0。 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. 因此,如何在sqlite中将默认值设置为TEXT列有所改变。 Thanks in advance :) 提前致谢 :)

EDIT 编辑
Here is the insert statement: 这是insert语句:

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

Here cv is the object of ContentValues which contains only the value for the column book_name . 这里cvContentValues的对象,它只包含列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.) (看起来好像你不能使用ALTER语句添加默认值,所以你必须重新创建你的表。)

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" 现在看到, 默认值设置为“abc”

Check sqllite documentation . 检查sqllite 文档

改变桌子,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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