Step 1: Configure pyodbc Python environment - Python driver for SQL Server | Microsoft Learn
官网教程如上。
安装python
从微软官网安装驱动到电脑
PIP安装pyodbc
import pyodbc
import pandas as pd
# pyodbc连接数据库必须先从官网在电脑上安装驱动才行
# https://learn.microsoft.com/en-us/sql/connect/python/pyodbc/step-1-configure-development-environment-for-pyodbc-python-development?view=azuresqldb-current
server = 'ip,1433'
database = 'sqlserver2017_db'
username = 'sa'
password = 'qwe20211114.'
print('------------------------------------')
cnxn = pyodbc.connect('DRIVER={ODBC Driver 18 for SQL Server};SERVER='+server+';DATABASE=' +
database+';UID='+username+';PWD=' + password + ";TrustServerCertificate=yes;")
print(cnxn)
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM INFORMATION_SCHEMA.TABLES')
row = cursor.fetchall()
print(row)
cursor.execute('select * from [Student]')
row = cursor.fetchall()
print(row)
print('------------------------------------')
df = pd.read_sql_query('select * from [Student]', cnxn)
print(df)