运行环境:
Linux 2.6.32-431.23.3.el6.i686 #1 SMP Thu Jul 31 14:37:53 UTC 2014 i686 i686 i386 GNU/Linux
CentOS release 6.5 (Final)
#-*-coding:utf8-*-
import pymssql
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
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.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):
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()
def main():
ms = MSSQL(host="xxx.xxx.xxx.xxx", user="sa", pwd="xxx", db="xxx")
resList = ms.ExecQuery("select name from users")
for name in resList:
print "".join(fullname)
if __name__ == '__main__':
main()
问题解决:
(1)缺少pymssql module
采用如下命令
pip install pymssql
(2)上述命令报错(报错信息没保留)
Linux下需要安装几个基础类库:
Cpython:
pip install Cpython ##Python包
freetds-dev:详情见(3)
yum install freetds-devel.x86_64
最后安装pymssql:
pip install pymssql
(3)freetds
查看软件源中版本
[root@xxx ~]# yum search freetds
Loaded plugins: security
====================================================== N/S Matched: freetds =======================================================
freetds-devel.i686 : Header files and development libraries for freetds
freetds-doc.i686 : Development documentation for freetds
asterisk-tds.i686 : Modules for Asterisk that use FreeTDS
freetds.i686 : Implementation of the TDS (Tabular DataStream) protocol
Name and summary matches only, use "search all" for everything.
安装
yum install freetds-devel
(4)pip版本过低
You are using pip version 7.1.2, however version 8.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
使用建议的命令pip install --upgrade pip
失败后
采用pip linstall -U pip
命令成功
(5)输出乱码问题
参考文献[1]中给出代码unicode中文乱码,各种decode,encode解决无果之后,type(name),发现name为tuple(元组)类型,再百度之,参考文献[4]完成tuple到str转换。
参考文献:
[1]http://www.cnblogs.com/qianlifeng/archive/2012/02/06/2340367.html
[2]http://blog.csdn.net/five3/article/details/16338191
[3]http://my.oschina.net/letiantian/blog/351237
[4]http://blog.csdn.net/sruru/article/details/7803208