您好,登錄后才能下訂單哦!
本文實例講述了Python使用pyodbc訪問數(shù)據(jù)庫操作方法。
數(shù)據(jù)庫連接
數(shù)據(jù)庫連接網(wǎng)上大致有兩種方法,一種是使用pyodbc,另一種是使用win32com.client,測試了很多遍,最終只有pyodbc成功,而且比較好用,所以這里只介紹這種方法
工具庫安裝
在此基礎(chǔ)上安裝pyodbc工具庫,在cmd窗口執(zhí)行如下語句安裝
pip install pyodbc
如果安裝了anaconda也可以使用conda install pyodbc
分享給大家供大家參考,具體如下:
檢驗是否可以正常連接數(shù)據(jù)庫檢查是否有一個Microsoft Access ODBC驅(qū)動程序可用于你的Python環(huán)境(在Windows上)的方法:
>>> import pyodbc
>>>[x for x in pyodbc.drivers() if x.startswith('Microsoft Access Driver')]
如果你看到一個空列表,那么您正在運行64位Python,并且需要安裝64位版本的“ACE”驅(qū)動程序。如果您只看到['Microsoft Access Driver (*.mdb)']并且需要使用.accdb文件,那么您需要安裝32位版本的“ACE”驅(qū)動程序
安裝64位的ODBC 驅(qū)動器:
64位ODBC驅(qū)動器的下載地址 https://www.microsoft.com/en-us/download/details.aspx?id=13255
直接安裝會報錯,所以我們需要修改一下文件AccessDatabaseEngine_X64.exe,先對其進行解壓,然后打開AccessDatabaseEngine_X64文件夾,有一個AceRedist.msi文件。用Orca軟件將AceRedist.msi打開,找到找到LaunchCondition里面的BLOCKINSTALLATION,刪除那一行數(shù)據(jù)并進行保存。然后再運行AceRedist.msi,就可以把64位的ODBC 驅(qū)動器安裝成功。
如果感覺上面的操作比較麻煩,可以直接下載億速云小編已經(jīng)處理過的版本。
下載地址:https://www.jb51.net/softs/695978.html
注意:
1、不用配置數(shù)據(jù)源
2、Orcad的下載地址 https://www.jb51.net/softs/16217.html
下面是經(jīng)過億速云小編測試過的代碼
access是2000的,理論上2010也可以。
import pyodbc DBfile = r"F:\python\caiji.mdb" # 數(shù)據(jù)庫文件需要帶路徑 print(DBfile) conn = pyodbc.connect(r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+ DBfile +";Uid=;Pwd=;") cursor = conn.cursor() SQL = "SELECT * from sites;" for row in cursor.execute(SQL): print(row) cursor.close() conn.close()
完整測試代碼
# -*-coding:utf-8-*- import pyodbc # 連接數(shù)據(jù)庫(不需要配置數(shù)據(jù)源),connect()函數(shù)創(chuàng)建并返回一個 Connection 對象 cnxn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=.\data\goods.mdb') # cursor()使用該連接創(chuàng)建(并返回)一個游標或類游標的對象 crsr = cnxn.cursor() # 打印數(shù)據(jù)庫goods.mdb中的所有表的表名 print('`````````````` goods ``````````````') for table_info in crsr.tables(tableType='TABLE'): print(table_info.table_name) l = crsr.execute("SELECT * from goods WHERE goodsId='0001'")# [('0001', '扇葉', 20, 'A公司', 'B公司', 2000, 2009)] rows = crsr.execute("SELECT currentStock from goods") # 返回的是一個元組 for item in rows: print(item) l = crsr.execute("UPDATE users SET username='lind' WHERE password='123456'") print(crsr.rowcount) # 想知道數(shù)據(jù)修改和刪除時,到底影響了多少條記錄,這個時候你可以使用cursor.rowcount的返回值。 # 修改數(shù)據(jù)庫中int類型的值 value = 10 SQL = "UPDATE goods " \ "SET lowestStock=" + str(value) + " " \ "WHERE goodsId='0005'" # 刪除表users crsr.execute("DROP TABLE users") # 創(chuàng)建新表 users crsr.execute('CREATE TABLE users (login VARCHAR(8),userid INT, projid INT)') # 給表中插入新數(shù)據(jù) crsr.execute("INSERT INTO users VALUES('Linda',211,151)") '''''' # 更新數(shù)據(jù) crsr.execute("UPDATE users SET projid=1 WHERE userid=211") # 刪除行數(shù)據(jù) crsr.execute("DELETE FROM goods WHERE goodNum='0001'") # 打印查詢的結(jié)果 for row in crsr.execute("SELECT * from users"): print(row) # 提交數(shù)據(jù)(只有提交之后,所有的操作才會對實際的物理表格產(chǎn)生影響) crsr.commit() crsr.close() cnxn.close()
1、連接數(shù)據(jù)庫
1)直接連接數(shù)據(jù)庫和創(chuàng)建一個游標(cursor)
cnxn =pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass') cursor =cnxn.cursor()
2)使用DSN連接。通常DSN連接并不需要密碼,還是需要提供一個PSW的關(guān)鍵字。
cnxn =pyodbc.connect('DSN=test;PWD=password') cursor =cnxn.cursor()
關(guān)于連接函數(shù)還有更多的選項,可以在pyodbc文檔中的 connect funtion 和 ConnectionStrings查看更多的細節(jié)
select ...from..where
)1)所有的SQL語句都用cursor.execute函數(shù)運行。如果語句返回行,比如一個查詢語句返回的行,你可以通過游標的fetch函數(shù)來獲取數(shù)據(jù),這些函數(shù)有(fetchone,fetchall,fetchmany).如果返回空行,fetchone
函數(shù)將返回None,而fetchall
和fetchmany
將返回一個空列。
cursor.execute("select user_id, user_name from users") row =cursor.fetchone() if row: printrow
2)Row這個類,類似于一個元組,但是他們也可以通過字段名進行訪問。
cursor.execute("select user_id, user_name from users") row =cursor.fetchone() print'name:', row[1] # access by column index print'name:', row.user_name # or access by name
3)如果所有的行都被檢索完,那么fetchone將返回None.
while 1: row= cursor.fetchone() ifnot row: break print'id:', row.user_id
4)使用fetchall函數(shù)時,將返回所有剩下的行,如果是空行,那么將返回一個空列。(如果有很多行,這樣做的話將會占用很多內(nèi)存。未讀取的行將會被壓縮存放在數(shù)據(jù)庫引擎中,然后由數(shù)據(jù)庫服務(wù)器分批發(fā)送。一次只讀取你需要的行,將會大大節(jié)省內(nèi)存空間)
cursor.execute("select user_id, user_name from users") rows =cursor.fetchall() for row in rows: printrow.user_id, row.user_name
5)如果你打算一次讀完所有數(shù)據(jù),那么你可以使用cursor本身。
cursor.execute("select user_id, user_name from users"): for row in cursor: printrow.user_id, row.user_name
6)由于cursor.execute
返回一個cursor,所以你可以把上面的語句簡化成:
for row in cursor.execute("select user_id, user_name from users"): printrow.user_id, row.user_name
7)有很多SQL語句用單行來寫并不是很方便,所以你也可以使用三引號的字符串來寫:
cursor.execute(""" select user_id, user_name from users where last_logon < '2001-01-01' and bill_overdue = 'y' """)
1)ODBC支持在SQL語句中使用一個問號來作為參數(shù)。你可以在SQL語句后面加上值,用來傳遞給SQL語句中的問號。
cursor.execute(""" select user_id, user_name from users where last_logon < ? and bill_overdue = ? """,'2001-01-01','y')
這樣做比直接把值寫在SQL語句中更加安全,這是因為每個參數(shù)傳遞給數(shù)據(jù)庫都是單獨進行的。如果你使用不同的參數(shù)而運行同樣的SQL語句,這樣做也更加效率。
3)python DB API明確說明多參數(shù)時可以使用一個序列來傳遞。pyodbc同樣支持:
cursor.execute(""" select user_id, user_name from users where last_logon < ? and bill_overdue = ? """, ['2001-01-01','y'])
cursor.execute("select count(*) as user_count from users where age > ?",21) row =cursor.fetchone() print'%d users' %row.user_count
1)數(shù)據(jù)插入,把SQL插入語句傳遞給cursor
的execute
函數(shù),可以伴隨任何需要的參數(shù)。
cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')") cnxn.commit()
cursor.execute("insert into products(id, name) values (?, ?)",'pyodbc', 'awesome library') cnxn.commit()
注意調(diào)用cnxn.commit()
函數(shù):你必須調(diào)用commit
函數(shù),否者你對數(shù)據(jù)庫的所有操作將會失效!當斷開連接時,所有懸掛的修改將會被重置。這很容易導致出錯,所以你必須記得調(diào)用commit
函數(shù)。
1)數(shù)據(jù)修改和刪除也是跟上面的操作一樣,把SQL語句傳遞給execute
函數(shù)。但是我們常常想知道數(shù)據(jù)修改和刪除時,到底影響了多少條記錄,這個時候你可以使用cursor.rowcount
的返回值。
cursor.execute("delete from products where id <> ?",'pyodbc') printcursor.rowcount, 'products deleted' cnxn.commit()
2)由于execute
函數(shù)總是返回cursor,所以有時候你也可以看到像這樣的語句:(注意rowcount放在最后面)
deleted =cursor.execute("delete from products where id <> 'pyodbc'").rowcount cnxn.commit()
同樣要注意調(diào)用cnxn.commit()
函數(shù)
1)由于使用單引號的SQL語句是有效的,那么雙引號也同樣是有效的:
deleted =cursor.execute("delete from products where id <> 'pyodbc'").rowcount
2)假如你使用的是三引號,那么你也可以這樣使用:
deleted =cursor.execute(""" delete from products where id <> 'pyodbc' """).rowcount
3)有些數(shù)據(jù)庫(比如SQL Server)在計數(shù)時并沒有產(chǎn)生列名,這種情況下,你想訪問數(shù)據(jù)就必須使用下標。當然你也可以使用"as"關(guān)鍵字來取個列名(下面SQL語句的"as name-count")
row =cursor.execute("select count(*) as user_count from users").fetchone() print'%s users' %row.user_count
4)假如你只是需要一個值,那么你可以在同一個行局中使用fetch
函數(shù)來獲取行和第一個列的所有數(shù)據(jù)。
count =cursor.execute("select count(*) from users").fetchone()[0] print'%s users' %count
如果列為空,將會導致該語句不能運行。fetchone()
函數(shù)返回None,而你將會獲取一個錯誤:NoneType不支持下標。如果有一個默認值,你能常常使用ISNULL,或者在SQL數(shù)據(jù)庫直接合并NULLs來覆蓋掉默認值。
maxid =cursor.execute("select coalesce(max(id), 0) from users").fetchone()[0]
在這個例子里面,如果max(id)
返回NULL,coalesce(max(id),0)
將導致查詢的值為0。
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python+MySQL數(shù)據(jù)庫程序設(shè)計入門教程》、《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)學運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。