sqlite3基本操作

226 阅读2分钟

database 增删改查

创建数据库

# 运行 sqlite3 时指定数据库名,若不存在就会创建该数据库
sqlite3 1.db

# 运行 sqlite3 时不指定数据库名,后面使用 .open FILENAME 创建或打开数据库
link@ubuntu:~/code/net/db$ sqlite3
SQLite version 3.24.0 2018-06-04 19:24:41
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open 1.db
sqlite>

删除数据库

# 使用 rm 删除数据库文件即可
link@ubuntu:~/code/net/db$ ls
1.db  3.db
link@ubuntu:~/code/net/db$ rm 1.db
link@ubuntu:~/code/net/db$ ls
3.db
link@ubuntu:~/code/net/db$

table 增删改查

增加 create

# 简单创建
# create table <表名> (<列名> <类型>, ...);
create table student (NAME char[32], AGE int);

# 防报错创建
# create table if not exists <表名> (<列名> <类型>, ...);
create table if not exists student (NAME char[32], AGE int);

# 复制表
create table stu_copies as select * from stu;

删除 drop

# 简单删除
# drop table <表名>
drop table student;

# 防报错删除
# drop table if exists <表名>
drop table if exists student;

修改 alter

修改表名

# 方式一
# alter table <表名> rename to <新表名>;
alter table student rename to stu;

# 方式二:创建新表,然后将旧表的数据插入到新表
# 旧表中的数据
sqlite> select * from stu;
xiaoming|25|99
xiaowang|20|59
# 输出创建表的语句,根据该语句创建新表
sqlite> .schema stu
CREATE TABLE IF NOT EXISTS "stu" (NAME char[32], AGE int, SCORE int);
# 复制创建表的语句,修改表名
sqlite> CREATE TABLE IF NOT EXISTS "student" (NAME char[32], AGE int, SCORE int);
# 将旧表的数据插入到新表
sqlite> insert into student select * from stu;
sqlite> select * from student;
xiaoming|25|99
xiaowang|20|59
# 删除旧表
sqlite> drop table stu;
sqlite> .tables
student
sqlite>

增加列

# alter table <表名> add column <列名> <类型>;
alter table student add column SCORE int;

删除列

修改列

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.

查询 .tables .schema

sqlite> .tables
student
sqlite> .schema student
CREATE TABLE student (NAME char[32], AGE int);
sqlite>

record 增删改查

增加 insert

# insert into <表名> [(列名1, 列名2, ...)] values (值1, 值2, ...);
insert into stu (NAME, AGE, SCORE) values ("xiaoming", 25, 99);
insert into stu values ("xiaowang", 20, 59);

删除 delete

# 删除所有记录
# delete from <表名>;

# 删除符合条件的记录
# delete from <表名> where <条件>;
delete from student where SCORE < 10;

修改 update

update student set AGE = 25, SCORE = 100 where NAME = "xiaoming";

查询 select

select * from stu;