首页 > 代码库 > Python连接sqlite3数据库

Python连接sqlite3数据库

import sqlite3
db = r"test.db"
drp_tb_sql = "drop table if exists staff"
crt_tb_sql = """
create table if not exists staff(
id integer primary key autoincrement unique not null,
name varchar(100),
city varchar(100)
);
"""
#连接数据库
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) values(?,?)" #?是占位符
cur.execute(insert_sql,(‘Tom‘,‘New York‘))
cur.execute(insert_sql,(‘Frank‘,‘Los Angeles‘))
con.commit()
#查询数据
select_sql = "select * from staff"
cur.execute(select_sql)
#返回一个list
date_set = cur.fetchall()
for row in date_set:
print(row)
cur.close()
con.close()

Python连接sqlite3数据库