欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python连接sql server乱码的解决方法

程序员文章站 2022-11-24 11:31:23
vi /etc/freetds/freetds.conf 复制代码 代码如下:[global]# tds protocol versiontds version = 8.0...

vi /etc/freetds/freetds.conf

复制代码 代码如下:

[global]
# tds protocol version
tds version = 8.0
client charset = utf-8
# a typical microsoft server
[server55]
host = 192.168.1.55
port = 1433
tds version = 8.0
vi /etc/odbc.ini
[dsn55]
description=my dsn
driver=tds
database=qq99
servername=server55

tsql -s server55 -u qq -p 123456 -d qq99
复制代码 代码如下:

#coding=utf-8
#!/usr/bin/python
import pyodbc
cnxn = pyodbc.connect("dsn=dsn55;uid=qq;pwd=123456")
cursor = cnxn.cursor()
cursor.execute('select * from orders where username=?','qq')
a=cursor.fetchall()
print 'pyodbc',a

关闭连接:
复制代码 代码如下:

csr.close()
del csr
conn.close()

python 使用pymssql连接sql server数据库

复制代码 代码如下:

#coding=utf-8
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# name: pymssqltest.py
# purpose: 测试 pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
#
# author: scott
#
# created: 04/02/2012
#-------------------------------------------------------------------------------

import pymssql


class mssql:
    """
    对pymssql的简单封装
    pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
    使用该库时,需要在sql server configuration manager里面将tcp/ip协议开启

    用法:

    """

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

    def __getconnect(self):
        """
        得到连接信息
        返回: conn.cursor()
        """
        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):
        """
        执行查询语句
        返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段

        调用示例:
                ms = mssql(host="localhost",user="sa",pwd="123456",db="pythonweibostatistics")
                reslist = ms.execquery("select id,nickname from weibouser")
                for (id,nickname) in reslist:
                    print str(id),nickname
        """
        cur = self.__getconnect()
        cur.execute(sql)
        reslist = cur.fetchall()

        #查询完毕后必须关闭连接
        self.conn.close()
        return reslist

    def execnonquery(self,sql):
        """
        执行非查询语句

        调用示例:
            cur = self.__getconnect()
            cur.execute(sql)
            self.conn.commit()
            self.conn.close()
        """
        cur = self.__getconnect()
        cur.execute(sql)
        self.conn.commit()
        self.conn.close()

def main():
## ms = mssql(host="localhost",user="sa",pwd="123456",db="pythonweibostatistics")
## #返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
## ms.execnonquery("insert into weibouser values('2','3')")

    ms = mssql(host="localhost",user="sa",pwd="123456",db="pythonweibostatistics")
    reslist = ms.execquery("select id,weibocontent from weibo")
    for (id,weibocontent) in reslist:
        print str(weibocontent).decode("utf8")

if __name__ == '__main__':
    main()

注意事项:
    使用pymssql进行中文操作时候可能会出现中文乱码,我解决的方案是:
文件头加上 #coding=utf8
sql语句中有中文的时候进行encode
   insertsql = "insert into weibo([userid],[weibocontent],[publishdate]) values(1,'测试','2012/2/1')".encode("utf8")
 连接的时候加入charset设置信息
    pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")