×

Python SQL SERVER

Python连接SQL Server入门

Kalet Kalet 发表于2019-05-10 16:49:58 浏览257 评论0

抢沙发发表评论

Python连接SQL Server入门

模块

import pyodbc


模块说明

pyodbc模块是用于odbc数据库(一种数据库通用接口标准)的连接,不仅限于SQL server,还包括Oracle,MySQL,Access,Excel等。


另外除了pyodbc还有其他几种连接SQL server的模块,感兴趣的可以在这里找到:https://wiki.python.org/moin/SQL%20Server


连接

传递odbc标准的连接字符串给 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 = pyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=192.168.1.1,3433;DATABASE=test;UID=user;PWD=password')

注意:不同的SQL server版本对应的DRIVER字段不同。对应关系如下:


{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)。建议选择与远程数据库版本相对应的Native Client。如果本地安装的Native Client是高版本,则DRIVER={SQL Server Native Client 11.0}需要填写的是本地的高版本。


使用pyodbc连接其他支持odbc的数据库方式可参考pyodbc官方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()


参考资料:


《pyodbc 官方文档》http://mkleehammer.github.io/pyodbc/

《pyodbc官方wiki》https://github.com/mkleehammer/pyodbc/wiki

《pyodbc的简单使用》http://my.oschina.net/zhengyijie/blog/35587


原文:https://blog.csdn.net/chroming/article/details/51541959 

群贤毕至

访客