import sqlite3
db = "test.db" #py工作目录下test.db数据库文件
drp_tb_sql = "drop table if exists staff"#sql语句:如果存在名为staff的表,则删除该表
#sql语句:如果不存在表staff,则创建一个表
crt_tb_sql = """
create table if not exists staff(
id integer primary key autoincrement unique not null,
name varchar(100),
city varchar(100),
age integer
);
"""
#1.创建了一个叫staff的表,它第一个为主键id,主键类型为integer,为自增长字段,键名唯一
#2.第二个键名为name,键的类型为varchar可变字符串型,长度为100
#3.第三个键名为city,键的类型也为varchar可变字符串型,长度为100
#4.第四个键名为age,键的类型为integer
#连接数据库
con = sqlite3.connect(db)#连接数据库,创建数据库连接对象
cur = con.cursor()#创建数据库的交互对象
#创建表staff
cur.execute(drp_tb_sql)#检查是否存在表,如存在,则删除
cur.execute(crt_tb_sql)#检查是否存在表,如不存在,则新创建表
#插入记录
insert_sql = "insert into staff (name,city,age) values (?,?,?)" #?为占位符,需要几个关键字
cur.execute(insert_sql,('Tom','New York',23)) #就打几个问号
cur.execute(insert_sql,('Frank','Los Angeles',34))
cur.execute(insert_sql,('Kate','Chicago',33))
cur.execute(insert_sql,('Thomas','Houston',88))
cur.execute(insert_sql,('Sam','Philadelphia',12))
con.commit()#数据库对象启动事务提交
#查询记录
select_sql = "select * from staff"#sql语言:进行查询操作
cur.execute(select_sql)
#返回一个list,list中的对象类型为tuple(元组)
date_set = cur.fetchall()#数据库中的所有行和列
name_list = []
for row in date_set:
for name1 in row:
name_list.append(name1)
print(name_list)
cur.close()#关闭数据库交互对象
con.close()#关闭数据库连接对象