Python連接SQL Server入門 模塊
import pyodbc
模塊說明
pyodbc
模塊是用于odbc數(shù)據(jù)庫(一種數(shù)據(jù)庫通用接口標(biāo)準(zhǔn))的連接,不僅限于SQL server,還包括Oracle,MySQL,Access,Excel等。
另外除了pyodbc
還有其他幾種連接SQL server的模塊,感興趣的可以在這里找到:https://wiki.python.org/moin/SQL%20Server
連接
傳遞odbc
標(biāo)準(zhǔn)的連接字符串給 connect
方法即可:
對于SQL server寫法如下:
conn?=?pyodbc.connect(r'DRIVER={SQL?Server?Native?Client?11.0};SERVER=test;DATABASE=test;UID=user;PWD=password')
注意:官方文檔中使用了port參數(shù),而官方wiki中連接SQL server是沒有port參數(shù)的。實際連接中發(fā)現(xiàn)加了port參數(shù)連不上(08001錯誤),port要寫在server參數(shù)中,逗號分割,如:
conn?=?pyodbc.connect(r'DRIVER={SQL?Server?Native?Client?11.0};SERVER=192.168.1.1,3433;DATABASE=test;UID=user;PWD=password')
注意:不同的SQL server版本對應(yīng)的DRIVER字段不同。對應(yīng)關(guān)系如下:
{SQL Server} - released with SQL Server 2000 {SQL Native Client} - released with SQL Server 2005 (also known as version 9.0) {SQL Server Native Client 10.0} - released with SQL Server 2008 {SQL Server Native Client 11.0} - released with SQL Server 2012
注意:使用pyodbc需要安裝微軟官方的Native Client(沒有安裝會報錯IM002),安裝SQL server management studio會自動附帶安裝(控制面板里可以看到安裝的版本)。如果沒有安裝過需要在https://msdn.microsoft.com/en-us/data/ff658533.aspx下載安裝(sqlncli.msi)。建議選擇與遠(yuǎn)程數(shù)據(jù)庫版本相對應(yīng)的Native Client。如果本地安裝的Native Client是高版本,則DRIVER={SQL Server Native Client 11.0}需要填寫的是本地的高版本。
使用pyodbc連接其他支持odbc的數(shù)據(jù)庫方式可參考pyodbc官方wiki。
獲取內(nèi)容
連接之后需要先建立cursor:
cursor?=?conn.cursor()
使用 execute
方法運(yùn)行SQL語句:
cursor.execute("select?user_id,?user_name?from?users")
execute
返回的仍然是cursor
。
使用 fetchone()
方法依次獲取結(jié)果中需要的內(nèi)容:
row?=?cursor.fetchone() if?row: ????print(row) print('name:',?row[1])?????????#?access?by?column?index print('name:',?row.user_name)??#?or?access?by?name
使用fetchall()
直接獲取所有execute結(jié)果作為一個list:
cursor.execute("select?user_id,?user_name?from?users") rows?=?cursor.fetchall() for?row?in?rows: ????print(row.user_id,?row.user_name)
由于execute
返回的是cursor本身,所以如果你需要一次直接獲取所有內(nèi)容可以直接使用cursor本身來獲?。?/p>
cursor.execute("select?user_id,?user_name?from?users"): for?row?in?cursor: ????print(row.user_id,?row.user_name)
增刪改
增刪改數(shù)據(jù)庫的內(nèi)容也是直接傳遞SQL語句給execute方法。但要注意運(yùn)行之后需要用commit提交變更:
cursor.execute("insert?into?products(id,?name)?values?('pyodbc',?'awesome?library')") conn.commit() cursor.execute("delete?from?products?where?id?<>??",?'pyodbc') print('Deleted?{}?inferior?products'.format(cursor.rowcount)) conn.commit()
參考資料:
《pyodbc 官方文檔》http://mkleehammer.github.io/pyodbc/ ?《pyodbc官方wiki》https://github.com/mkleehammer/pyodbc/wiki ?《pyodbc的簡單使用》http://my.oschina.net/zhengyijie/blog/35587