import sqlite3 as sql
#1、建立连接
conn=sql.connect("test.db") #如果数据库文件存在则打开 没有则新建
#2、建立cursor
c=conn.cursor()
#3、首先判断表是否存在,如果存在 创建同名表会出错
res=c.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name='datas' ''')
if not res :
c.execute('''create table datas (id int primary key not null,name text not null,texts text not null); ''')
#4、插入记录
c.execute('''insert into datas (id,name,texts) values(1,"zhangsan","今天天气真好"); ''')
c.execute('''insert into datas (id,name,texts) values(2,"admin","你们要去逛街吗"); ''')
c.execute('''insert into datas (id,name,texts) values(3,"lisi","我们想去公园"); ''')
conn.commit()
conn.close()
#7、查询数据表内容
conn=sql.connect("test.db")
c=conn.cursor()
res=c.execute('''select * from datas''')
for x in res:
print(x)
res=c.execute('''select * from user''')
for x in res:
print(x)
'''
e:\>python ex16.py
(1, 'zhangsan', '今天天气真好')
(2, 'admin', '你们要去逛街吗')
(3, 'lisi', '我们想去公园')
(1, 'zhangsan', '123456')
(2, 'admin', '123456')
(3, 'lisi', '123456')
'''
|