码迷,mamicode.com
首页 > 数据库 > 详细

python操作SqlServer

时间:2018-12-07 21:23:50      阅读:332      评论:0      收藏:0      [点我收藏+]

标签:信息   enc   测试   imp   sqlserver   span   host   数据库   etc   

  python操作sqlserver需要使用pymssql模块

import pymssql

class Mysql():
    def __init__(self,host,user,pwd,db):
        self.host = host
        self.user = user
        self.pwd = pwd
        self.db = db

    def connectDB(self):
        if not self.db:
            raise(NameError,"没有设置数据库信息")
        self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
        cur = self.conn.cursor()
        if not cur:
            raise(NameError,"连接数据库失败")
        else:
            return cur

    def ExecQuery(self,sql):
        ‘‘‘
        查询数据库
        :param sql: 
        :return: 
        ‘‘‘
        cur = self.connectDB()
        cur.execute(sql)
        res = cur.fetchall()
        self.conn.close()
        return res

    def ExecNonQuery(self,sql):
        ‘‘‘
        非查询操作
        :param sql: 
        :return: 
        ‘‘‘
        cur = self.connectDB()
        cur.execute(sql)
        self.conn.commit()
        self.conn.close()

ms = Mysql(host="127.0.0.1",user="lary",pwd="lary123",db="testdb")
res = ms.ExecQuery("select * from users")
for i in res:
    print(i)

sql="update users set name=‘%s‘ where id=1"%u测试
print(sql)
ms.ExecNonQuery(sql.encode(utf-8))

 

python操作SqlServer

标签:信息   enc   测试   imp   sqlserver   span   host   数据库   etc   

原文地址:https://www.cnblogs.com/iamluoli/p/10077604.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!