python操作SqlServer
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'))