Python連接SQL Server入門
模塊
import pymssql
模塊說明
pymssql
模塊是用於sql server數據庫(一種數據庫通用接口標准)的連接。另外pyodbc不僅限於SQL server,還包括Oracle,MySQL,Access,Excel等。
另外除了pymssql,pyodbc
還有其他幾種連接SQL server的模塊,感興趣的可以在這里找到:https://wiki.python.org/moin/SQL%20Server
連接
傳遞pymssql
標准的連接字符串給 connect
方法即可:
對於SQL server寫法如下:
conn = pyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=test;DATABASE=test;UID=user;PWD=password')
注意:官方文檔中使用了port參數,而官方wiki中連接SQL server是沒有port參數的。實際連接中發現加了port參數連不上(08001錯誤),port要寫在server參數中,逗號分割,如:
conn = pymssql.connect(r'SERVER=192.168.1.1,3433;DATABASE=test;UID=user;PWD=password;db=database')
注意:不同的SQL server版本對應的DRIVER字段不同。對應關系如下:
使用pymssql連接其他支持mssql的數據庫方式可參考pymssql官方wiki。
獲取內容
連接之后需要先建立cursor:
cursor = conn.cursor()
使用 execute
方法運行SQL語句:
cursor.execute("select user_id, user_name from users")
execute
返回的仍然是cursor
。
使用 fetchone()
方法依次獲取結果中需要的內容:
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結果作為一個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本身,所以如果你需要一次直接獲取所有內容可以直接使用cursor本身來獲取:
cursor.execute("select user_id, user_name from users"): for row in cursor: print(row.user_id, row.user_name)
增刪改
增刪改數據庫的內容也是直接傳遞SQL語句給execute方法。但要注意運行之后需要用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()
轉載from http://blog.csdn.net/chroming/article/details/51541959