前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python操作sqlserver数据库

Python操作sqlserver数据库

原创
作者头像
python亦希
发布2022-01-19 14:14:36
1.2K0
发布2022-01-19 14:14:36
举报
文章被收录于专栏:python理论

1.安装epel源:

yum -y install epel-release

2.安装pip:

yum -y install python-pip

3.清缓存:

yum clean all

4.升级pip:

pip install --upgrade pip

5.安装pymssql:

pip install pymssql

代码语言:txt
复制
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import pymssql
 5 
 6 class MSSQL:
 7     def __init__(self,host,user,pwd,db):
 8         self.host = host
 9         self.user = user
10         self.pwd = pwd
11         self.db = db
12 
13     def __GetConnect(self):
14         if not self.db:
15             raise(NameError,"没有设置数据库信息")
16         self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
17         cur = self.conn.cursor()
18         if not cur:
19             raise(NameError,"连接数据库失败")
20         else:
21             return cur
22 
23     def ExecQuery(self,sql):
24         cur = self.__GetConnect()
25         cur.execute(sql)
26         resList = cur.fetchall()
27 
28         #查询完毕后必须关闭连接
29         self.conn.close()
30         return resList
31 
32     def ExecNonQuery(self,sql):
33         cur = self.__GetConnect()
34         cur.execute(sql)
35         self.conn.commit()
36         self.conn.close()
37 
38 ms = MSSQL(host="10.7.125.1",user="sa",pwd="test",db="test1")
39 reslist = ms.ExecQuery("select "字段" from "表名" where "条件字段"=5")
40 for i in reslist:
41     print (i)
42 
43 newsql="update "表名" set "字段"='%s' where "条件字段"="改前值"%u'改后值'
44 print (newsql)
45 ms.ExecNonQuery(newsql.encode('utf-8'))

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档