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;U)

注意:官方文档中使用了port参数,而官方wiki中连接SQL server是没有port参数的。实际连接中发现加了port参数连不上(08001错误),port要写在server参数中,逗号分割,如:

conn = pymssql.connect(r'SERVER=192.168.1.1,3433;DATABASE=test;U)

注意:不同的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