COUNT 字段不正确或语法错误 (0) (SQLExecDirectW)')

COUNT field incorrect or syntax error (0) (SQLExecDirectW)')

我在 运行 运行我的代码时收到错误消息,如下所示:

DBAPIError: (pyodbc.Error) ('07002', '[07002] [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error (0) (SQLExecDirectW)')
[SQL: INSERT INTO #temptable VALUES (?,?,?,?,?,?,?,?,?)]
(Background on this error at: http://sqlalche.me/e/14/dbapi)

我曾经 运行 将我的数据导入 SQL:

conn= urllib.parse.quote_plus("DRIVER={SQL Server}; SERVER=ABCDEF; Database=ABC; UID=user123; PWD=user123;")
engine = sa.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(conn))

with engine.begin() as con:
    con.execute("""
         CREATE TABLE #temptable (
            [a] NVARCHAR(100)
            , [b] NVARCHAR(100)
            , [c] NVARCHAR(100)
            , [d] NVARCHAR(100)
            , [e] NVARCHAR (100)
            , [f] NVARCHAR (100)
            , [g] NVARCHAR(100)
            , [h] FLOAT
            , [i] NVARCHAR(100))""")

    sql_insert = f"INSERT INTO #temptable VALUES (?,?,?,?,?,?,?,?,?)"
    con.execute(sql_insert, data.values.tolist())

    sql_merge = """
        MERGE data_final AS Target
        USING #temptable AS Source
            ON Source.a = Target.a
       
        WHEN NOT MATCHED BY Target THEN
            INSERT ([a], [b], [c], [d], [e], [f], [g], [h], [i]) 
            VALUES (source.a, source.b, source.c, source.d, source.e, source.f, source.g, source.h, source.i)
        
        WHEN MATCHED THEN 
            UPDATE SET
            Target.h = Source.h
            , Target.i = Source.i;"""
    con.execute(sql_merge)
    con.execute("""DROP TABLE IF EXISTS #temptable;""")

有人知道我的代码有什么问题吗? 因为在我添加更多 2 个参数之前一切正常

根据标签猜测,当您应该使用 executemany 时,您似乎正在将 pandas 数据帧生成的列表列表发送到 execute。顺便说一下,考虑 to_numpy as recommended on the DataFrame.values 文档。最后,预处理语句不需要 f-string。

sql_insert = "INSERT INTO #temptable VALUES (?,?,?,?,?,?,?,?,?)" 
vals = data.to_numpy().tolist()

con.executemany(sql_insert, vals)

实际上,您甚至不需要临时 table 但它可能有助于处理非常大的数据集 运行 MERGE 单个集而不是迭代值。

sql_merge = """MERGE data_final AS Target 
               USING (VALUES(?,?,?,?,?,?,?,?,?)) 
                  AS Source ([a], [b], [c], [d], [e], [f], [g], [h], [i])
                    
               ON Source.a = Target.a 

               WHEN NOT MATCHED BY Target THEN
               INSERT ([a], [b], [c], [d], [e], [f], [g], [h], [i]) 
               VALUES (source.a, source.b, source.c, source.d, source.e, 
                       source.f, source.g, source.h, source.i) 

               WHEN MATCHED THEN 
               UPDATE SET Target.h = Source.h
                        , Target.i = Source.i;
            """
vals = data.to_numpy().tolist()

con.executemany(sql_merge, vals)