1、通过pip在Python中安装SQLServer的驱动程序。
在cmd命令中输入:python -m pip install pymssql
2、建立数据库以及测试表。
--drop database test; create database test; use test; create table app_users ( user_id int identity(1,1) not null, user_code varchar(60) not null, user_name varchar(256) null, primary key(user_id) ); insert into app_users(user_code, user_name) values('9001', 'jzh'); insert into app_users(user_code, user_name) values('9002', 'chanpinxue.cn'); insert into app_users(user_code, user_name) values('9003', 'chanpinxue.cn');
3、测试代码
#coding=utf-8 # 测试SQLServer import pymssql class cts_mssql(): def query(): try: conn = pymssql.connect(host="127.0.0.1:1433", user="sa", password="", database="test", charset="utf8") except pymssql.connector.Error as e: print('连接失败{}'.format(e)) cursor = conn.cursor() try: # 查询 sql_query = 'select user_code, user_name from app_users' cursor.execute(sql_query) for user_code, user_name in cursor: print(user_code, user_name) except pymssql.connector.Error as e: print('查询异常{}'.format(e)) finally: cursor.close() conn.close() # if __name__ == '__main__'的意思是: # 当.py文件被直接运行时,if __name__ == '__main__'之下的代码块将被运行; # 当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行。 if __name__ == '__main__': cts_mssql.query()