官方文檔html
準備工做,引用包,並創建鏈接python
import sqlite3 db_conn = sqlite3.connect('example.db')
db_conn.execute(r''' CREATE TABLE stocks ( uuid text, date text, trans text, symbol text, qty real, pricereal ) ''')
也能夠判斷表是否存在,若是不存在就新建sql
db_conn.execute(r''' CREATE TABLE IF NOT EXISTS stocks ( uuid text, date text, trans text, symbol text, qty real, pricereal ) ''')
組裝原始sql語句進行插入,這種使用字符串拼接的方法不安全,可能會被sql注入數據庫
db_conn.execute(r''' INSERT INTO stocks VALUES ('2001-01-11', 'BUY', 'RHAT', 100, 35.14) ''') db_conn.commit()
db_conn.execute(r''' INSERT INTO stocks VALUES (:1, :2, :3, :4, :5) ''', ('2001-01-11', 'BUY', 'RHAT', 100, 35.14) ) db_conn.commit()
db_conn.execute(r''' INSERT INTO stocks VALUES (:1, :2, :3, :4, :5) ''', ('2001-01-11', 'BUY', 'RHAT', 100, 35.14) ) db_conn.commit()
db_conn.execute(r''' INSERT INTO stocks VALUES (:aa, :bb, :cc, :dd, :ee) ''', ('2001-01-11', 'BUY', 'RHAT', 100, 35.14) ) db_conn.execute(r'''INSERT INTO stocks VALUES (:aa, :bb, :cc, :dd, :ee) ''', {'aa': '2001-01-11', 'bb': 'BUY', 'cc': 'RHAT', 'dd':100, 'ee': 35.14} ) db_conn.execute(r'''INSERT INTO stocks (date, trans, symbol, qty, price) VALUES (:aa, :bb, :cc, :dd, :ee) ''', {'aa': '2001-01-11', 'bb': 'BUY', 'cc': 'RHAT', 'dd':100, 'ee': 35.14} ) db_conn.commit()
這三種方式就和字符串的format的用法差很少數組
executemany
插入多條數據能夠把問號替換成上面講的其餘佔位符號安全
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ] db_conn.executemany(r''' INSERT INTO stocks VALUES (?,?,?,?,?) ''', purchases) db_conn.commit()
fetchone 查詢單條數據 fetchall 查詢全部數據 fetchmany 查詢指定數目的數據 它們的返回結果是tuple或者tuple數組,若是沒有數據就返回Nonefetch
for row in c.execute('SELECT * FROM stocks ORDER BY price'): print(row)
提交與回滾操做必須仍是由db_conn
來進行處理ui
import sqlite3 db_conn = sqlite3.connect('example.db') db_cur = db_conn.cursor() #使用遊標建表 db_cur.execute(r''' CREATE TABLE IF NOT EXISTS stocks (date text, trans text, symbol text, qty real, price real) ''') #使用遊標插入數據 db_cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)") #數據庫鏈接進行提交操做 db_conn.commit() db_conn.close()
executescript
一次性執行多句sqldb_conn.executescript(r''' create table person( firstname, lastname, age ); create table book( title, author, published ); insert into book(title, author, published) values ( 'Dirk Gently''s Holistic Detective Agency', 'Douglas Adams', 1987 ); ''')
with
的使用python上下文協議文檔code
db_conn = sqlite3.connect(":memory:") db_conn.execute("create table person (id integer primary key, firstname varchar unique)") # 將會在with語句結束後自動調用db_conn.commit()來進行提交 with db_conn: db_conn.execute("insert into person(firstname) values (?)", ("Joe",)) # 在拋異常時將會自動調用db_conn.rollback()來進行回滾,可是異常仍然會被拋出 try: with db_conn: db_conn.execute("insert into person(firstname) values (?)", ("Joe",)) except sqlite3.IntegrityError: print("couldn't add Joe twice")