You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python3.6+的f-string通过SQLAlchemy连接本地无密码SQL Server并对接Pandas

使用SQLAlchemy连接无验证本地SQL Server并导出到Pandas DataFrame(Python3.6+)

1. 安装必要依赖

先安装所需Python包:

pip install sqlalchemy pyodbc pandas

2. 用f-string构建连接字符串

针对无需用户名密码的本地SQL Server,采用Windows身份验证(Trusted Connection),用f-string动态拼接参数:

from sqlalchemy import create_engine
import pandas as pd

# 替换为你的服务器名称(如localhost或localhost\SQLEXPRESS)和目标数据库名
server_name = "localhost\SQLEXPRESS"
db_name = "YourDatabaseName"

# 用f-string生成SQLAlchemy连接URL
conn_url = f"mssql+pyodbc://@{server_name}/{db_name}?driver=ODBC+Driver+17+for+SQL+Server&Trusted_Connection=yes"

3. 连接数据库并读取数据到DataFrame

创建引擎后,直接用Pandas将查询结果存入df变量:

# 初始化SQLAlchemy引擎
engine = create_engine(conn_url)

# 替换为你的查询语句,示例为读取整张表
query = "SELECT * FROM YourTableName"
df = pd.read_sql_query(query, engine)

# 可选:验证数据
print(df.head())

注意事项

  • 确认SQL Server的TCP/IP协议已开启:在SQL Server配置管理器中找到对应实例,启用TCP/IP后重启服务。
  • ODBC驱动版本可按需替换:示例用ODBC Driver 17 for SQL Server,若系统安装了18版本,直接修改驱动名即可。
  • 服务器名称需准确:默认实例用localhost,命名实例格式为服务器名\实例名。

内容的提问来源于stack exchange,提问作者Shane S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:31:06