首页 > 解决方案 > ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] 使用 sqlalchemy 将 Dataframe/csv 文件导出到 sql server table 2018 的 Python 代码

问题描述

我正在尝试使用 sqlalchemy 将 Dataframe 导出到 MS Azure DB 表

下面是代码,

import sqlalchemy
import urllib
import pyodbc
from sqlalchemy import event

params = urllib.parse.quote_plus("Driver={ODBC Driver 17 for SQL Server};Server=tcp:***.database.windows.net,1433;DATABASE=***;UID=***@xyz.com;PWD=***;Authentication=ActiveDirectoryPassword")
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
df = pd.read_csv(r'C:\Users\path\aaa.csv')
@event.listens_for(engine, 'before_cursor_execute')
def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany):
       if executemany:
            cursor.fast_executemany = True
            cursor.commit()

conn=engine.connect()
print(conn)

连接似乎成功了!

它说

<sqlalchemy.engine.base.Connection 对象在 0x000001C839972F88>

但重要的部分是出口,这是不成功的!

from sqlalchemy.types import Integer, Text, String, DateTime

...

table_name = 'dbo.rpt_performance_comment'

dat.to_sql(
    table_name,
    engine,
    if_exists='replace',
    index=False,
    chunksize=500,
    dtype={
        "id": Integer,
        "pr_comment_id": Integer,
        "pr_comment": Text
    }
)

下面是我得到的错误

ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]指定的架构名称“ **@xyz.com”要么不存在,要么您存在没有使用它的权限。(2760)(SQLExecDirectW)')[SQL:CREATE TABLE [dbo.rpt_performance_comment](pr_comment_id INTEGER NULL,pr_comment VARCHAR(max)NULL)](此错误的背景:http://sqlalche .me/e/f405)*

我也尝试过使用 pyodbc ,如下所示。但连接本身并不成功。

https://stackoverflow.com/a/57431228/15945458

请通过数据框或 csv 文件帮助我完成导出部分。

标签: pythondataframesqlalchemyodbc

解决方案


推荐阅读