记录python连接sqlserver,
第一步: 打开管理工具,在驱动程序配置 sql server Native Client 11.0
当然 安装SQL Server 2016(13.x)时会安装Microsoft SQL Server Native Client 11.0。
第二步: pip install pyodbc
第三步,导入pyodbc包,配置好数据库连接字符串就可以了
import pymssql import pyodbc print(__name__) #第一种不需要输入用户名密码,通过windows方式连接数据库 # cnxn_str = ("Driver={SQL Server Native Client 11.0};" # "Server=xxx;" # "Database=xxx;" # "Trusted_Connection=yes;") #第二种需要输入密码通过用户名密码形式连接数据库 cnxn_str=("Driver={SQL Server Native Client 11.0};" "Server=xxx;" "Database=xxx;" "UID=xxx;" "PWD=xx;") cnxn = pyodbc.connect(cnxn_str) # 使用cursor.execute从针对数据库的查询中检索结果集。 cursor = cnxn.cursor() cursor.execute("SELECT top 1 * FROM [test]") row = cursor.fetchone() while row: print (row) row = cursor.fetchone()
最后附上官网的连接
Step 3 - Connecting to SQL using pyodbc - Python driver for SQL Server | Microsoft Learn