import sqlite3 db = "test.db" #py工作目录下test.db数据库文件drp_tb_sql = "drop table if exists staff"#sql语句:如果存在表,则删除名为staff的表#sql语句:如果不存在表,则创建一个表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()#创建数据库的交互对象 #创建表staffcur.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()#数据库连接对象启动事务提交#修改记录################################################################fix = "update staff set name = '盛夏' where id = 1" cur.execute(fix)con.commit()select_sql = "select * from staff"cur.execute(select_sql)print(cur.fetchall())print("*"*20)#删除记录##################################################################dele = "delete from staff where id =1"cur.execute(dele)con.commit()select_sql = "select * from staff"cur.execute(select_sql)print(cur.fetchall()) cur.close()#关闭数据库交互对象con.close()#关闭数据库连接对象