1. 数据库的安装
离线模式下: sudo dpkg -i *.deb在线模式下:sudo apt-get install sqlite3
2,.数据库基本命令:
1)系统命令 , 都以' . ' 开头
.exit 和 .quit 退出数据库
.table 查看数据库中存在的表
.schema 查看表的结构,也就是查看如何创建的表,范围为数据库中所有的表
2)sql语句, 都以‘ ; ’结尾
说明:文中所有的stuinfo都为所操作的表名
1-- 创建表
create table stuinfo(id integer, name text, age integer, score float);
注意:列名在前,此列所存放的数据的类型在后
2-- 插入一条记录
insert into stuinfo values(1001, 'zhangsan', 18, 80);
insert into stuinfo (id, name, score) values(1002, 'lisi', 90);
3-- 查看数据库记录
查询所有表中记录:
select * from stuinfo;
查询表中指定字段的记录:
select * from stuinfo where score = 80;//查询stuinfo表中score字段的值为80的记录
select * from stuinfo where score = 80 and name= 'zhangsan';
select * from stuinfo where score = 80 or name='wangwu';
select name,score from stuinfo;
select * from stuinfo where score >= 85 and score < 90;
4-- 删除一条记录
也可以删除指定字段的记录:
delete from stuinfo where id=1003 and name='zhangsan';
5-- 更新一条记录
update stuinfo set age=20 where id=1003;
update stuinfo set age=30, score = 82 where id=1003;
6-- 删除一张表
drop table stuinfo;
7-- 增加一列
alter table stuinfo add column sex char;
8-- 删除一列
sqlite中没有直接删除一列的命令,所以我们创建一个新表来复制我们要修改的表,再复制时只需要不复制我们想删除的那个字段即可,然后再删除旧表,再把新表的名修改为原来的名字即可。
create table stu as select id, name, score from stuinfo;
drop table stuinfo;
alter table stu rename to stuinfo;
数据库设置主键:
create table info(id integer primary key autoincrement, name vchar);
设置主键的目的:
在数据库中,主键的作用是保证表中每一行的唯一性,同时也可以用来连接其他表。
主键是一个特殊的列,它的值必须唯一,并且不能为空。当你在创建数据库表时,可以指定某个列为主键列。一般来说,主键会使用自增长的整数来标识每一行,这样可以保证主键值的唯一性。
关于使用主键使得某字段变为自增字段的详情请看此文章: