引入包:import sqlite3
1.连接(打开)数据库
import sqlite3 a = sqlite3.connect('test.db') #打开路径数据库
a:数据库对象
连接数据库,如果数据库不存在,那么它就会被创建,返回一个数据库对象
2.创建表
import sqlite3 a = sqlite3.connect('test.db') #打开路径数据库 b=a.cursor() #创建cursor游标b sql='''create table company (id int primary key not null, name text not null, age int not null);''' b.execute(sql) #执行sql语句 a.commit() #提交数据库操作 a.close() #关闭数据库连接
上面是创建一个名为company的表,id name age 为参数
建表数据格式:数据名称 数据类型 其它类型
primary key:主键
not null:非空
分号表示是一个sql语句
(建议用可视化工具建表)
3.插入数据
a = sqlite3.connect('test.db') #打开路径数据库 b=a.cursor() #获取游标 sql='''insert into company (id,name,age) values(1,'张三',30) ''' b.execute(sql) #执行sql语句 a.commit() #提交数据库操作 a.close() #关闭数据库连接
insert into company (id,name,age) 插入表company,后面是表里的参数
values(1,'张三',30) 要存入的数据
可以多行插入
3.查询数据
a = sqlite3.connect('test.db') #打开路径数据库 b = a.cursor() #获取游标 sql ='select id,name,age from company' #从compan获得id,name,age c = a.execute(sql) for d in c: print(d) a.close() #关闭数据库连接
打印结果是一个元组(1,'张三',30),可以使用d[0]等得到单个数据
4.更新数据
a = sqlite3.connect('test.db') #打开路径数据库 b = a.cursor() #获取游标 sql ='update company set name= '李四' where id=1' a.execute(sql) a.close() #关闭数据库连接
#表company中,id为1的name改为李四
5.删除数据
sql ='delete from company where id=1;' a.execute(sql)
从表单company中删除id为1的所有数据
6.删除表
sql = 'drop table company;' a.execute(sql)
删除表company