以SQLite和PySqlite為例來學習Python DB API
Python應用編程需要用到的針對不同數(shù)據(jù)庫引擎的數(shù)據(jù)庫接口:http://wiki.python.org/moin/DatabaseInterfaces
Python標準的DB API 2.0見:http://www.python.org/dev/peps/pep-0249/
本文將以SQLite和PySqlite為例來學習Python DB API。
pysqlite是一個sqlite為python 提供的api接口,它讓一切對于sqlit的操作都變得異常簡單。
從Python2.5起,pysqlite作為Python的一個標準模塊。在使用標準庫時,它被簡稱為sqlite3模塊。
sqlite3標準庫,詳見:http://docs.python.org/3.3/library/sqlite3.html
基本的學習內容如下:
1.創(chuàng)建一張表
# filename:create.py import sqlite3 # 創(chuàng)建連接對象 conn = sqlite3.connect('E:/code/py/db/test.db') # 創(chuàng)建一個游標對象 cur = conn.cursor() # 創(chuàng)建數(shù)據(jù)表的sql語句 createtb_sql = """create table test( id integer, name text, age integer);""" # 調用execute()執(zhí)行create_sql語句 cur.execute(createtb_sql) # 關閉游標 cur.close() # 關閉連接 conn.close()
2.簡單的插入數(shù)據(jù)
# filename:insert.py import sqlite3 # 創(chuàng)建連接對象 conn = sqlite3.connect('E:/code/py/db/test.db') # 創(chuàng)建一個游標對象 cur = conn.cursor() # 向數(shù)據(jù)表中插入數(shù)據(jù)的sql語句 ''' insert_sql = """ insert into test values(1, 'huhu', 20); insert into test values(2, 'hengheng', 18); insert into test values(3, 'huahua', 18); """ ''' insert_sql = """ insert into test values(1, 'huhu', 20); """ # 調用execute()執(zhí)行insert sql語句 # execute一次只能執(zhí)行一條語句 cur.execute(insert_sql) # 提交事務 conn.commit() # 關閉游標 cur.close() # 關閉連接 conn.close()
3.查詢
# filename:select.py import sqlite3 # 創(chuàng)建連接對象 conn = sqlite3.connect('E:/code/py/db/test.db') # 創(chuàng)建一個游標對象 cur = conn.cursor() # 查詢數(shù)據(jù)表的sql語句 select_sql = """ select * from test;""" # 調用execute()執(zhí)行select sql語句 cur.execute(select_sql) ''' while True: # fetchone()把查詢的結果集的下一行作為序列或者None row = cur.fetchone() if row == None: break print(row) ''' ''' # fetchall()把查詢的結果集的所有行作為序列的序列 for row in cur.fetchall(): print(row) ''' # 迭代對象遍歷 for row in cur: print(row) # 關閉游標 cur.close() # 關閉連接 conn.close()
4.刪除數(shù)據(jù)
# filename:delete.py import sqlite3 # 創(chuàng)建連接對象 conn = sqlite3.connect('E:/code/py/db/test.db') # 創(chuàng)建一個游標對象 cur = conn.cursor() # delete語句 delete_sql = """delete from test""" # execute()執(zhí)行sql語句 cur.execute(delete_sql) # commit()提交事務 conn.commit() # 關閉游標 cur.close() # 關閉連接 conn.close()
以上四步的運行結果:
5.一次插入多條數(shù)據(jù)
# filename:insertmany.py import sqlite3 # 創(chuàng)建連接對象 conn = sqlite3.connect('E:/code/py/db/test.db') # 創(chuàng)建一個游標對象 cur = conn.cursor() # 向數(shù)據(jù)表中插入數(shù)據(jù)的sql語句 insert_sql = """insert into test values(?, ?, ?)""" # 調用execute()執(zhí)行insert sql語句 # execute一次只能執(zhí)行一條語句 for line in open('E:/code/py/db/data.txt'): fields = line.split(',') vals = [f for f in fields] cur.execute(insert_sql,vals) # 提交事務 conn.commit() # 關閉游標 cur.close() # 關閉連接 conn.close()
data.txt:
1,huhu,18
2,hengheng,18
3,lq,20
運行結果:
6.插入數(shù)據(jù)的方法(參數(shù)綁定,executemany的使用):
# inserts.py import sqlite3 # 創(chuàng)建連接對象 conn = sqlite3.connect('E:/code/py/db/test.db') # 創(chuàng)建一個游標對象 cur = conn.cursor() # 向數(shù)據(jù)表中插入數(shù)據(jù)的sql語句 # 最簡單的insert形式 insert_sql1 = """insert into test values(1, 'huhu', 20);""" # execute()一次只能執(zhí)行一條語句 cur.execute(insert_sql1) # 參數(shù)綁定 # execute()第二個參數(shù):位置參數(shù)或者字典類型參數(shù) insert_sql2 = """insert into test values(?, ?, ?)""" cur.execute(insert_sql2, (2,'hengheng',18)) insert_sql3 = """insert into test values(:id, :name, :age)""" cur.execute(insert_sql3, {'id':3, 'name':'lq', 'age':18}) # executemany()第二個參數(shù):列表類型參數(shù),適用于迭代器和生成器 l = [(4, 'huhu', 18), (5, 'hh', 18), (6, 'lq', 18)] cur.executemany(insert_sql2, l) # 利用生成器實現(xiàn) def l_generator(): l = [(7, 'huhu', 18), (8, 'hh', 18), (9, 'lq', 18)] for t in l: yield(t) cur.executemany(insert_sql2, l_generator()) # 提交事務 conn.commit() # 關閉游標 cur.close() # 關閉連接 conn.close()
運行結果:
7.帶條件的的update、delelte和select語句
(1)update
# filename:update.py import sqlite3 # 創(chuàng)建連接對象 conn = sqlite3.connect('E:/code/py/db/test.db') # 創(chuàng)建一個游標對象 cur = conn.cursor() # update語句 update_sql = """update test set name = 'noname' where id = ?""" # execute()和executem()執(zhí)行sql語句 x = (1, ) cur.execute(update_sql, x) y = (2, ) cur.execute(update_sql, y) l = [(3, ),(4, ),(5, )] cur.executemany(update_sql, l) # commit()提交事務 conn.commit() # 關閉游標 cur.close() # 關閉連接 conn.close()
運行結果:
(2)delete
# filename:delete1.py import sqlite3 # 創(chuàng)建連接對象 conn = sqlite3.connect('E:/code/py/db/test.db') # 創(chuàng)建一個游標對象 cur = conn.cursor() # delete語句 delete_sql = """delete from test where id = ?""" # execute()和executemany()執(zhí)行sql語句 cur.execute(delete_sql, (1, )) cur.executemany(delete_sql, [(2, ), (3, )]) # commit()提交事務 conn.commit() # 關閉游標 cur.close() # 關閉連接 conn.close()
運行結果:
(3)select
# filename:select1.py import sqlite3 # 創(chuàng)建連接對象 conn = sqlite3.connect('E:/code/py/db/test.db') # 創(chuàng)建一個游標對象 cur = conn.cursor() # 查詢數(shù)據(jù)表的sql語句 select_sql = """ select * from test where id = ?;""" # 調用execute()執(zhí)行select sql語句 x = (8, ) cur.execute(select_sql, x) ''' # 在executemany中,不能執(zhí)行select語句 y = [(2, ), (3, )] cur.executemany(select_sql, y) ''' # 迭代對象遍歷 for row in cur: print(row) # 關閉游標 cur.close() # 關閉連接 conn.close()
運行結果:
sqlite3標準庫相比Python DB API 2.0,增加了一個較為方便的函數(shù)executescript函數(shù)(一次可以執(zhí)行多條sql),介紹如下:
This is a nonstandard convenience method for executing multiple SQL statements at once. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter.
sql_script can be an instance of str or bytes.
Example:
import sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" 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', ); """)
好了這篇文章就為大家介紹到這了,希望大家以后多多支持腳本之家。
相關文章
微軟開源最強Python自動化神器Playwright(不用寫一行代碼)
這篇文章主要介紹了微軟開源最強Python自動化神器Playwright(不用寫一行代碼),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01Python連接數(shù)據(jù)庫使用matplotlib畫柱形圖
這篇文章主要介紹了Python連接數(shù)據(jù)庫使用matplotlib畫柱形圖,文章通過實例展開對主題的相關介紹。具有一定的知識參考價值性,感興趣的小伙伴可以參考一下2022-06-06Pandas實現(xiàn)自定義Excel格式并導出多個sheet表
pandas默認整合XlsxWriter驅動,可以自動化處理excel操作,并提供公式、設置單元格格式、可視化分析圖片等操作,本文就來和大家詳細聊聊2023-05-05