sqlite-SQL-表的创建、销毁、修改

创建表:

creat table <table_name>(field type,field type..);

sqlite3存储数据的类型

NULL:标识一个NULL值

INTERGER:整数类型

REAL:浮点数

TEXT:字符串

BLOB:二进制数


sqlite3存储数据的约束条件
Sqlite常用约束条件如下:
PRIMARY KEY - 主键:---:理解:某种格式、特性的数据 (比如:ID)
1)主键的值必须唯一,用于标识每一条记录,如学生的学号
2)主键同时也是一个索引,通过主键查找记录速度较快
3)主键如果是整数类型,该列的值可以自动增长
NOT NULL - 非空:
约束列记录不能为空,否则报错
UNIQUE - 唯一:
除主键外,约束其他列的数据的值唯一
CHECK - 条件检查:
约束该列的值必须符合条件才可存入
DEFAULT - 默认值:
列数据中的值基本都是一样的,这样的字段列可设为默认值

销毁表:

drop <table_name>;

更改表名:

alter table <table_name> rename to <new_name>;

修改表结构:

添加列:

alter table <table_name> add column <field>;
删除列:

(因为sqlite3 不支持drop column,详情看本文末尾)

操作步骤:

A.alter table people rename to temp;
B.create table people(id,name,age);

C.insert  into  people  select  id,name,age  from temp;

----------------------------------------------------------------------------

更多内容请往下看:

sqlite--record: 主键约束条件--唯一性测试

t_table3:

sqlite> create table t_table3(gas_1_0 real,gas_2_0 real,primary key(gas_1_0,gas_2_0));

sqlite> insert into t_table3 values(0.9,2.2);

sqlite> insert into t_table3 values(1.2,2.0);

sqlite> insert into t_table3 values(1.2,1.9);

sqlite> select * from t_table3;

gas_1_0     gas_2_0   

----------  ----------

0.9         2.2       

1.2         2.0       

1.2         1.9  

sqlite> insert into t_table3 values(1.2,1.9);

Error: UNIQUE constraint failed: t_table3.gas_1_0, t_table3.gas_2_0

gasdata_table :

sqlite> create table gasdata_table as select * from t_table3;

sqlite> select * from gasdata_table

   ...> ;

gas_1_0     gas_2_0   

----------  ----------

0.9         2.2       

1.2         2.0       

1.2         1.9   

sqlite> insert into gasdata_table values(1.2,1.9);

sqlite> select * from gasdata_table;

gas_1_0     gas_2_0   

----------  ----------

0.9         2.2       

1.2         2.0       

1.2         1.9       

1.2         1.9   

:通过CREATE TABLE ... AS SELECT方式创建的数据表,将与SELECT查询返回的结果集具有相同的Schema信息,将会包含结果集返回的所有数据,但是不包含缺省值和主键等约束信息。

-------------------------------------------------------------

注意:(来自网络)

今天在做数据库升级时,碰到要对原来数据库中一张表的一个字段名进行修改,但是用:

alter table tablename rename column oldColumnName to newColumnName;

始终不成功,后面查阅相关信息:

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

sqlite支持一个更改表内容的有限子集,就是说在sqlite更改表的命令中,只允许用户重命名表名或者增加多一个列到一个的表中。而重命名一个字段名和删除一个字段、或者增加和删除系统规定的参数这些操作是不可能的。

解决办法:

例如:在上面的操作过程中,我们在people表中新添加了一个字段addr,要删除这个字段,直接用sqlite的语句时无法完成的。

我们可以这样干:

A.将people表重命名为temp;

B.重新创建people表;

C.将temp表中的相应字段内容复制到people表中。

D.删除temp表

操作如下:

A.alter table people rename to temp;

B.create table people(id,name,age);

C.insert  into  people  select  id,name,age  from temp;

posted @ 2015-11-16 17:30  cuiz_book  阅读(1045)  评论(0编辑  收藏  举报