import sqlite3
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute('create table category(id primary key, sort, name)')
cur.execute("insert into category values(1, 1, 'computer')")
cur.execute("insert into category values(?, ?, ?)", (2, 3, 'literature'))
cur.execute('select * from category')
print(cur.fetchall())
# 输出:[(1, 1, 'computer'), (2, 3, 'literature')]
for row in cur.execute('select * from category'):
print(row[0], row[1])
1 1
2 3
con.commit() # 事务提交
con.rollback() # 事务回滚
cur.close()
con.close()
import sqlite3
con = sqlite3.connect('sales.db')
con.execute('create table book(id primary key, price, name)')
import sqlite3
Con = sqlite3.connect('sales.db')
Cur = Con.cursor()
books = [('021', 25, '大学计算机'),
('022', 30, '大学英语'),
('023', 18, '艺术欣赏'),
('024', 35, '高级语言程序设计')]
Cur.execute("insert into book(id, price, name) values('001', 33, '大学计算机多媒体')")
Cur.execute("insert into book(id, price, name) values(?,?,?)", ('002', 28, '数据库基础'))
Cur.executemany('insert into book(id, price, name) values(?,?,?)', books)
Cur.execute('Update book set price=? where name = ?', (25, '大学英语'))
n = Cur.execute('delete from book where price = ?', (25,))
print('删除了',n.rowcount,'行记录')
Con.commit()
Cur.close()
Con.close()
删除了 2 行记录
import sqlite3
Con = sqlite3.connect('sales.db')
Cur = Con.cursor()
Cur.execute('select id, price, name from book')
for row in Cur:
print(row)
(‘002’, 28, ‘数据库基础’)
(‘001’, 33, ‘大学计算机多媒体’)
(‘023’, 18, ‘艺术欣赏’)
(‘024’, 35, ‘高级语言程序设计’)