本文实例讲述了Python实现的连接mssql数据库操作。分享给大家供大家参考,具体如下:
1. 目标数据sql2008 R2 ComPrject=>TestModel
2. 安装python 连接mssql 模块
运行
1
|
pip install pymssql - 2.2 . 0.dev0 - cp36 - cp36m - win_amd64.whl
|
运行完毕 查看是否成功 pip -m list
3. 编写python 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
import time
import pymssql
#import decimal
class MSSQL:
def __init__( self ,host,user,pwd,db):
self .host = host
self .user = user
self .pwd = pwd
self .db = db
def GetConnect( self ):
if not self .db:
raise (NameError, '没有目标数据库' )
self .connect = pymssql.connect(host = self .host,user = self .user,password = self .pwd,database = self .db,charset = 'utf8' )
cur = self .connect.cursor()
if not cur:
raise (NameError, '数据库访问失败' )
else :
return cur
def ExecSql( self ,sql):
cur = self .GetConnect()
cur.execute(sql)
self .connect.commit()
self .connect.close()
def ExecQuery( self ,sql):
cur = self .GetConnect()
cur.execute(sql)
resList = cur.fetchall()
self .connect.close()
return resList
def main():
ms = MSSQL(host = "192.168.0.108" , user = "sa" , pwd = "sa" , db = "ComPrject" )
resList = ms.ExecQuery( "select *from TestModel" )
print (resList)
if __name__ = = '__main__' :
main()
input ( "执行完成:" )
|
4. 运行效果
备注:如果读取中文出现乱码,需要修改varchar=>nvarchar
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://www.cnblogs.com/linsu/p/8488515.html