SQLite 学习 1
一些基础知识
1.数据库后缀名是自定义的,如student.sqlite3,ldci.db。 2.SQL语句是以;结束的 3.主键:primary key 自增长主键:integer primary key 4. 一、创建数据表 打开终端,输入“sqlite3 stu.db”(stu.db是数据库名称,若存在,则打开已有的文件,若不存在,就会创建它) 1、创建简单的数据表 sqlite>create table student(id integer primary key,name text,age text); 2、在指定的数据库创建表 sqlite>attach database '/users/lxy/stu.db' as newstu; sqlite> create table newstu.text(id integer primary key,age text); 这里先通过ATTACH DATABASE命令将一个已经存在的数据库文件attach到当前的连接中,之后再通过指定数据库名newstu的方式在目标数据库中创建数据表text。 如果我们在创建数据表时没有指定数据库名,那么会在当前连接的main数据库中创建该表,在一个连接中只能有一个main数据库。如果需要创建临时表,就无需指定数据库名. 3、如果当前创建的数据表名已经存在,即与已经存在的表名、视图名和索引名冲突,那么本次创建操作将失败并报错。 如 sqlite> create table student(id integer primary,age text); 如果在创建表时加上"IF NOT EXISTS"从句,那么本次创建操作将不会有任何影响,即不会有错误抛出,除非当前的表名和某一索引名冲突。 sqlite> create table if not exists student(id integer primary key,age text); 4、根据已有的表创建新表 sqlite> create table student1 as select *from student; 通过该方式创建的数据表将与SELECT查询返回的结果集具有相同的Schema信息,但是不包含缺省值和主键等约束信息。然而新创建的表将会包含结果集返回的所有数据。 5、创建带约束的表 (1)主键约束 --->直接在字段的定义上指定主键。 sqlite> create table newtable(first integer primary key asc); --->在所有字段定义完后在定义表的数约束 sqlite> create table text2( ( 2 )唯一性约束 1)直接在字段的定义上指定唯一性约束条件 sqlite> create table text3(first integer quique); 2)在所有字段定义完毕后,再定义表的唯一性约束。 sqlite> create table text4( ...> unique(first,second)
( 3 )非空约束(NOT NULL) 在SQLite中,NULL值被视为和其他任何值都是不同的,如下例 sqlite> select count (*)from text3; sqlite> insert into text3 values(null); sqlite> select count (*)from text3; 可见,插入的null值插入成功。 sqlite> create table text5(fitsr integer not null);
( 4)检查性约束(CHECK) sqlite> create table new(first integer CHECK(first < 1)); 插入的值为5,违反了字段first<1的检查行约束 二、表的修改(ALTER TABLE) SQLite对ALTER TABLE命令支持的非常有限,仅仅是修改表名和添加新字段。 1、修改表名 sqlite> create table stu(first integer); 可以看到,stu已经被重命名为newstu。 SOLite中表名的修改只能在再同一个数据库中,一旦表名被修改,该表已经存在的索引不会受到影响,但依赖该表的的视图和触发器要重新修改定义。
2、新增字段 sqlite> alter table newstu add column second integer; sqlite> .schema newstu 关于ALTER TABLE最后需要说明的是,在SQLite中该命令的执行时间是不会受到当前表行数的影响,也就是说,修改有一千万行数据的表和修改只有一条数据的表所需的时间几乎是相等 。 三、对表进行操作
一些指令 .database ---查看数据库 .tables ---查看所有表
创建数据库:sqlite3 ldci.db 查看数据库:.database
查看表的命令:.tables 显示表结构: .schema表名
(1)插入数据 sqlite> create table student(id integer primary key,age text); (2) 查询 查询所有数据 sqlite> select *from student; 查询序号为1的数据 sqlite> select *from student where id=1; 根据年龄从小到大排序 sqlite> select *from student order by age;
根据年龄从大到小排序 sqlite> select *from student order by age desc;2|李四|15 1|张三|12 3|王五|11
修改数据 sqlite> update student set age=30 where id=1;把序号为1的age改为30. sqlite> select *from student where id=1; 删除某一列数据 sqlite> delete from student where id=2; 可以看到,序号为2的数据已被删除。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |