标签:
准备工作:
cmd 命令行下安装pymssql:
pip install pymssql
查询的数据库如下:
代码如下:
#coding=utf-8 import pymssql class MSSQLOBJ(object): def __init__(self, user, password, dbname, host=‘local‘, port=1433): self._connect = pymssql.connect(server=host, port=port, user=user, password=password, database=dbname, charset=‘UTF-8‘, as_dict=True) self._cursor = self._connect.cursor() def execute_query(self, sql): self._cursor.execute(sql) return self._cursor.fetchall() def execute_non_query(self, sql): self._cursor.execute(sql) self._connect.commit() def close(self): self._cursor.close() self._connect.close() if __name__ == ‘__main__‘: sqlobj = MSSQLOBJ(‘chenfp‘, ‘111111‘, ‘test‘, ‘127.0.0.1‘, 1433) res = sqlobj.execute_query(‘select top 4 username,department,age from test.dbo.info‘) for v in res: print(v[‘username‘]+v[‘department‘]+v[‘age‘])
输入如下:
----------------------------------
陈姗姗 技术部 25 哈成鹏 爱炒股事业部 22 袁卉 技术部 25 陈典强 技术部 30
标签:
原文地址:http://www.cnblogs.com/nzyjlr/p/4933501.html