Python连接MS SQL Server

Python访问各个数据库需要需要借助对应的modules,比如MySQL需要MySQLdb,SQL Server需要pymssql。
两个模块大同小异,都遵循Python Database API

Python Database API

Python Database API,只需要了解Connection Objects和Cursor Objects的常用方法。

Connection Objects

方法 含义
cursor 返回一个Cursor对象
commit 提交事务
rollback 回滚
close 关闭连接

Cursor Objects

方法 含义
execute 执行一条SQL语句
executemany 执行多条语句
fetchone 获取一行数据
fetchmany 获取n行的数据
fetchall 获取未返回的数据
close 关闭游标

了解了Python Database API值之后安装pymssql
安装好之后开工了。
如果是连接本地的SQL Server需要在 SQL Server Configuration 中打开TCP/IP协议

Python连接MS SQL Server_第1张图片
SQL Server Configuration

代码如下:

#coding=utf-8
import pymssql
conn = pymssql.connect(host='127.0.0.1',user='sa',
                       password='hello',database='NPKW',
                      charset="utf8")
#查看连接是否成功
print conn
cursor = conn.cursor()
sql = 'select * from contacts'
cursor.execute(sql)
#用一个rs变量获取数据
rs = cursor.fetchall()
print rs

输出如下:



[(1, u'20111612210028', u'ettingshausen', u'', u'', u'', u'', u'', u'', u'', u'', u'')]

你可能感兴趣的:(Python连接MS SQL Server)