在web開(kāi)發(fā)中亏娜,經(jīng)常要與數(shù)據(jù)庫(kù)打交道焕窝。數(shù)據(jù)庫(kù)分為關(guān)系型數(shù)據(jù)庫(kù)和非關(guān)系型數(shù)據(jù)庫(kù)。其中最常用的是關(guān)系型數(shù)據(jù)庫(kù)维贺,也叫SQL數(shù)據(jù)庫(kù)它掂。
那么Python中如何操作SQL數(shù)據(jù)庫(kù)呢?
操作環(huán)境:Python 3.6.0
SQL版本:sqlite3
下面我們以圖書(shū)為例溯泣,在Python控制臺(tái)進(jìn)行演示操作虐秋。
創(chuàng)建連接
conn = sqlite3.connect('book.db')
c = conn.cursor()
cursor叫做游標(biāo),用來(lái)執(zhí)行SQL語(yǔ)句垃沦。
創(chuàng)建表格
sql = "create table BOOK(
title text,
author text,
price integer,
pubdate text
)"
c.execute(sql)
conn.commit()
SQL支持的數(shù)據(jù)類型有Text客给,Integer等。
添加數(shù)據(jù)
sql = "insert into BOOK values ('python','jason',36,'2017-1-14')"
c.execute(sql)
sql = "insert into BOOK values ('http','tom',42,'2016-2-14')"
c.execute(sql)
conn.commit()
修改數(shù)據(jù)
sql = "update BOOK set title='flask' where rowid=1"
c.execute(sql)
conn.commit()
刪除數(shù)據(jù)
sql = "delete from BOOK where title='flask'"
c.execute(sql)
conn.commit()
搜索數(shù)據(jù)
sql = "select * from BOOK"
#執(zhí)行SQL之后肢簿,得到corsor對(duì)象靶剑◎卟Γ可以使用for循環(huán)遍歷出結(jié)果。
rows= c.execute(sql)
for row in books:
print(row)
'''result:
('python','jason',36,'2017-1-14')
('http','tom',42,'2016-2-14')'''
上面我們介紹了創(chuàng)建表格以及對(duì)表格的四種操作抬虽。除了這些官觅,還有幾點(diǎn)需要注意的地方;
- 以刪除數(shù)據(jù)為例。實(shí)際工作中阐污,刪除的數(shù)據(jù)往往是從外部獲取得到的休涤,并不是寫(xiě)死的。
title = ('linux',)
#insecure
sql = "delete BOOK where title={}".format('linux')
c.execute(sql)
#do this instead
sql = "delete BOOK where title=?"
c.execute(sql,title)
我們使用參數(shù)化查詢笛辟,來(lái)防止SQL注入功氨。參數(shù)用tuple的形式傳遞。
- 搜索數(shù)據(jù)的結(jié)果手幢,可以用fetchall()來(lái)處理捷凄。
sql = "select * from BOOK"
c.execute(sql)
lst = c.fetchall()
for row in lst:
print(row)
'''result:
('python','jason',36,'2017-1-14')
('http','tom',42,'2016-2-14')'''
當(dāng)然,除了fetchall()以外围来,還有fetchone()跺涤,fetchmany()等。