参数化数据框的列

Parametize columns of a dataframe

我想在 cursor.execute 函数中对列和数据框进行参数化。我正在使用 pymssql,因为我喜欢我可以命名参数化列的事实。然而,我仍然不知道如何正确地告诉 python 我指的是一个特定的数据框,我想使用这个列。这是我的代码的最后一部分(我已经测试了与我的数据库等的连接并且它有效):

with conn:
    cursor = conn.cursor()
    cursor.execute("""insert into [dbo].[testdb] (day, revenue) values (%(day)s, %(revenue)s)""", dataframe)
    result = cursor.fetchall()

    for row in result:
        print(list(row))

我收到这个错误:

ValueError                                Traceback (most recent call last)
<ipython-input-52-037e289ce76e> in <module>
     10 with conn:
     11     cursor = conn.cursor()
---> 12     cursor.execute("""insert into [dbo].[testdb] (day, revenue) values (%(day)s, %(revenue)s""", dataframe)
     13     result= cursor.fetchall()
     14 

src\pymssql.pyx in pymssql.Cursor.execute()

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1477     def __nonzero__(self):
   1478         raise ValueError(
-> 1479             f"The truth value of a {type(self).__name__} is ambiguous. "
   1480             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1481         )

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

很难猜出为什么要在插入查询后使用 fetchall:fetchall 通常用于 select 查询。

execute 通常将一行插入 table。如果您想一次插入多行,PEP-249 建议使用 executemany。但问题在于该参数预计是 records 的可迭代对象:如果您使用位置参数(?:1,.. .),或者如果您使用命名参数,则为可迭代的映射。数据框不是那样的。但是您可以使用 .to_dict(orient='record) 将其转换为字典列表。所以这应该有效(它在我使用 SQLite3 的测试中有效):

cursor.executemany("""insert into [dbo].[testdb] (day, revenue) values (%(day)s, %(revenue)s)""",
                dataframe.to_dict(orient='record'))

我明白我的问题是什么了。由于我将数据框转换为字典(使用 dataframe.to_dict'index'),该字典是一个嵌套字典。我用 dataframe[0] 引用它并且它起作用了。以防万一有人遇到同样的问题。