【问题标题】:Problem loading data into SQL Server using python使用 python 将数据加载到 SQL Server 时出现问题
【发布时间】:2021-07-09 09:25:29
【问题描述】:

我正在使用 pyodbc 库。当我将数据加载到本地服务器(没有密码)时,它似乎正在工作。但是,当我尝试将数据加载到另一台服务器时,似乎出现了一些错误。

# Connect to SQL Server
conn = pyodbc.connect('Driver={SQL Server};'
                  'Server=xxxxxx;'
                  'Database=test_preproduction;'
                  'Trusted_Connection=yes;'
                  'UID=xxxxxx;'
                  'PWD=xxxxxxxxx;')
cursor = conn.cursor()

# Insert DataFrame to Table
for row in df.itertuples():
    cursor.execute('''
                INSERT INTO test_preproduction.[dbo].[people_info] (Column1, Column2, Column3, Column4, Column5, Column6, Column7, Column8)
                VALUES (?,?,?,?,?,?,?,?)
                ''',
                row.Column1, 
                row.Column2,
                row.Column3,
                row.Column4,
                row.Column5,
                row.Column6,
                row.Column7,
                row.Column8
                )
conn.commit()

我收到了这个错误:

pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]无效的对象名称't​​est_preproduction.dbo.people_info'。(208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]无法准备语句。(8180)")

【问题讨论】:

  • 那么,在该服务器上的数据库test_preproductiondbo 模式中实际上是否有一个名为people_info 的表?如果不是,那么这将解释错误。您必须先创建一个表,然后才能插入它(或者使用SELECT .. INTO)。顺便说一句,在INSERT 中明确指定数据库名称不是一个好习惯——您在连接时已经指定了数据库,如果您未能保持名称同步,您会感到非常意外。跨度>
  • 让连接决定数据库。不要将其硬编码到您的应用程序使用的每个 sql 语句中 - 这会使您的代码更难(即创建更多工作)移动到不同的环境。
  • 怎么连连生成一个表相关的错误?使用UID=...;PWD=...; 进行SQL 登录身份验证,或使用Trusted_Connection=yes; 进行域/Windows 身份验证,但不要将两者混用。我很惊讶它没有因登录错误而失败。

标签: sql-server pyodbc


【解决方案1】:
 try:
     connection.autocommit = False 
     for row in df.itertuples():
         cursor.execute("INSERT INTO [dbo].[people_info] (Column1, Column2, Column3, Column4, Column5, Column6, Column7, Column8)" "VALUES (?,?,?,?,?,?,?,?);", (row))
     connection.commit()
 

这对我有用。由于未调用值“row”,这就是您从错误消息中得到错误部分(SQLExecDirectW)的原因。如果 autocommit 为 True,将为每条记录提交提供的 SQL 语句,从而导致您可能希望避免的重复行条目。希望这有助于调试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多