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

SQLAlchemy连接SQL Server成功但无法写入DataFrame为表,如何解决?

解决DataFrame写入SQL Server报错“Invalid object name 'sqlite_master'”的问题

问题原因

你直接将pyodbc.connect()创建的连接对象传给to_sql时,pandas无法自动识别这是SQL Server连接,会默认套用SQLite的语法逻辑,执行了SQLite特有的sqlite_master表查询——而SQL Server不存在这个系统表,因此触发报错。

解决方案

改用SQLAlchemy Engine作为to_sql的con参数,让pandas能根据数据库类型生成适配的SQL语句。

修改后的代码示例

from sqlalchemy import create_engine
import pandas as pd

try:
    # 用SQLAlchemy创建连接引擎
    connection_string = (
        f"mssql+pyodbc://{server_name}/{database_name}?"
        f"driver=ODBC+Driver+17+for+SQL+Server&trusted_connection={tcon}"
    )
    sql_server_engine = create_engine(connection_string)

    # 测试连接
    with sql_server_engine.connect() as conn:
        result = conn.execute('SELECT 1')
        for row in result:
            print(row)
    print("SQL Server connection established successfully.")  
    
    # 写入DataFrame到数据库
    App_test.to_sql(
        'App_test', 
        schema='Test_Data', 
        con=sql_server_engine, 
        if_exists='replace', 
        index=False
    )

except Exception as e:
    print(f"Error: {e}")

关键说明

  • SQLAlchemy的create_engine会通过连接字符串中的mssql+pyodbc标识,告知pandas当前连接的是SQL Server,从而生成适配的表存在性检查语句(替代SQLite的sqlite_master查询)。
  • 若使用SQL Server身份验证而非Windows集成验证,需在连接字符串中添加UID=你的用户名;PWD=你的密码参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:32:36