python对sqlite3进行增删查改的操作
Python操作sqlite3(增删查改)
import sqlite3
con=sqlite3.connect('G:\sqllite3\demo.db')
cur=con.cursor()
def create_tab():
sql='''create table if not exists lin( pno INTEGER primary key , name VARCHAR not null, age INTEGER ) '''
try:
cur.execute(sql)
print('创建表成功')
except Exception as e:
print(e)
print('创建表失败')
finally:
cur.close()
con.close()
def insert_tab():
sql="insert into lin(name,age) values(?,?)"
try:
cur.execute(sql,['李某',15])
con.commit()
print('插入成功')
except Exception as e:
print(e)
con.rollback()
print("插入失败")
finally:
cur.close()
con.close()
def delete_tab():
sql='delete from lin where pno=?'
try:
cur.execute(sql,(3,))
con.commit()
print('删除成功')
except Exception as e:
print(e)
con.rollback()
print('删除失败')
finally:
cur.close()
con.close()
def update_tab():
sql="update lin set name=? where pno=?"
try:
cur.execute(sql,['赵九',2])
con.commit()
print('修改成功')
except Exception as e:
print(e)
con.rollback()
print('打印失败')
finally:
cur.close()
con.close()
def select_tab():
sql="select * from lin"
try:
cur.execute(sql)
person_all=cur.fetchall()
#遍历出数据
for person in person_all:
print(person)
except Exception as e:
print(e)
con.rollback()
print('查询失败')
finally:
cur.close()
con.close()
def inserts_tab():#插入多条数据
sql="insert into lin (name,age) values(?,?)"
try:
cur.executemany(sql,[('赵一',11),('赵二',12),('赵三',13),('赵四',14)])
con.commit()
print('插入多条记录成功')
except Exception as e:
print(e)
con.commit()
print('插入多条记录失败')
finally:
cur.close()
con.close()
if __name__ == '__main__':
create_tab()#先创建表,这里运行一次,把他注释掉,已经创建好了,不然会报错
#insert_tab()
#inserts_tab()
delete_tab()
#select_tab()
#update_tab()
这是一个简单的操作sqllite3的增删查改操作
还没有评论,来说两句吧...