# By Vamei
import sqlite3
conn = sqlite3.connect("test.db")
c = conn.cursor()
books = [(1, 1, 'Cook Recipe', 3.12, 1),
(2, 3, 'Python Intro', 17.5, 2),
(3, 2, 'OS Intro', 13.6, 2),
]
# execute "INSERT"
c.execute("INSERT INTO category VALUES (1, 1, 'kitchen')")
# using the placeholder
c.execute("INSERT INTO category VALUES (?, ?, ?)", [(2, 2, 'computer')])
# execute multiple commands
c.executemany('INSERT INTO book VALUES (?, ?, ?, ?, ?)', books)
conn.commit()
conn.close()
插入数据同样可以使用execute()来执行完整的SQL语句。SQL语句中的参数,使用"?"作为替代符号,并在后面的参数中给出具体值。这里不能用Python的格式化字符串,如"%s",因为这一用法容易受到SQL注入攻击。
我也可以用executemany()的方法来执行多次插入,增加多个记录。每个记录是表中的一个元素,如上面的books表中的元素。
查询
在执行查询语句后,Python将返回一个循环器,包含有查询获得的多个记录。你循环读取,也可以使用sqlite3提供的fetchone()和fetchall()方法读取记录:
代码如下:
# By Vamei
import sqlite3
conn = sqlite3.connect('test.db')
c = conn.cursor()
# retrieve one record
c.execute('SELECT name FROM category ORDER BY sort')
print(c.fetchone())
print(c.fetchone())
# retrieve all records as a list
c.execute('SELECT * FROM book WHERE book.category=1')
print(c.fetchall())
# iterate through the records
for row in c.execute('SELECT name, price FROM book ORDER BY sort'):
print(row)
更新与删除
你可以更新某个记录,或者删除记录:
本站所有资源全部来源于网络,若本站发布的内容侵害到您的隐私或者利益,请联系我们删除!
合作方式
Copyright © 2004-2018 https://www.gxlcms.com/. All Rights Reserved.
豫ICP备19030742号