python操作sqlite3基本操作
import sqlite3con = sqlite3.connect('./db/user.db')cur = con.cursor()sql = 'create table if not exists user(id integer primary key, name text, age integer)'cur.execute(sql)# 插入一条 or 多条def create_user(
·
import sqlite3
con = sqlite3.connect('./db/user.db')
cur = con.cursor()
sql = 'create table if not exists user(id integer primary key, name text, age integer)'
cur.execute(sql)
# 插入一条 or 多条
def create_user():
# insert
# cur.execute('insert into user values(?,?,?)', (1, 'adleytales', 3))
# insert manay
list = [
(2, 'para', 13),
(3, 'aliya', 16),
(4, 'balan', 12),
(5, 'okok', 10),
]
cur.executemany('insert into user values(?,?,?)', list)
# 查询
def select_users():
cur.execute('select * from user')
result = cur.fetchall()
# [(1, 'adleytales', 3), (2, 'para', 13), (3, 'aliya', 16), (4, 'balan', 12), (5, 'okok', 10)]
print(result)
def select_users2():
cur.execute('select * from user')
result = cur.fetchone()
print(result) # (1, 'adleytales', 3)
def select_users3():
cur.execute('select * from user')
result = cur.fetchmany(2)
print(result) # [(1, 'adleytales', 3), (2, 'para', 13)]
# 更新
def update_user():
cur.execute('update user set name=? where id =?', ('new_adleytales', 5))
# 删除
def delete_user():
cur.execute('delete from user where id=?', (3,))
# create_user()
# select_users()
# select_users2()
select_users3()
# update_user()
# delete_user()
con.commit()
con.close()
更多推荐
已为社区贡献14条内容
所有评论(0)