linux下安装pymssql

各版本的下载地址:https://pypi.python.org/pypi/pymssql/


Windows可以下载installer文件,直接是编译好的,可以直接安装


Linux下需要安装几个基础类库:

Cpython:pip install Cpython        ##python包

freetds-dev:yum install freetds-devel.x86_64 / apt-get install freetds-dev   ##linux包

最后安装pymssql: pip install pymssql


测试:

import pymssql	
conn = pymssql.connect(host=host, user=user, password=password, 
		database=database, charset='utf8', port='1433', as_dict=False)
cursor = conn.cursor()
sql = "select * from payment where id in (59,60)"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
	print row


简单封装:适用于大量数据查询,提高性能

#encoding=utf-8
import pymssql

class CursorWapper:
	def __init__(self, cursor):
		self.cursor = cursor
		
	def query(self, sql):
		db_cursor = self.cursor
		self.cursor.execute(sql)
		if db_cursor.description:
			names = [x[0] for x in db_cursor.description]
		def iterwrapper():                
			row = db_cursor.fetchone()
			while row:
				yield dict(zip(names, row))
				row = db_cursor.fetchone()
		class IterBetter:
			def __init__(self, iter):
				self.i = iter
			def __iter__(self):
				while 1:    
					yield self.i.next()
			def __nonzero__(self):
				if hasattr(self, "__len__"):
					return len(self) != 0
		out = IterBetter(iterwrapper())
		out.__len__ = lambda: db_cursor.rowcount!=0 and 1 or 0  ##当前版本有一个bug,rowcount始终为-1,如果有结果
		return out
		
def test(host, user, password, database):
	conn = pymssql.connect(host=host, user=user, password=password, 
			database=database, charset='utf8', port='1433', as_dict=False)
	cursor = conn.cursor()
	return CursorWapper(cursor)
	
if __name__=='__main__':
	newdb = test(host, user, password, database)
	sql = "select * from payment where id in (59,60)"
	results = newdb.query(sql)
	for row in results:
		print row




你可能感兴趣的:(python,pymssql)