【问题标题】:Pandas cx_Oracle - Insert failingPandas cx_Oracle - 插入失败
【发布时间】:2021-02-28 05:23:00
【问题描述】:

我有这段代码可以使用 cx_oracle 向表中插入数据,但出现了一些错误。

我的数据如下所示:

[['BOB', 20190619, 118.16, 118.38, 116.05, 117.8, 'No', 117.8, 117.8, 117.8, 0.0, 0.0, 0.0, nan, nan, nan, nan]

我对代码的尝试是这样的:

sql='INSERT INTO stockstats VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16)'

n = 0
for i in df.iterrows():
  cursor_1.execute(sql,df_list[n])
  n += 1

cursor_1.execute(sql,df_list[n])
cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number

我也试过了,遇到了同样的问题:

sql = 'INSERT INTO stockstats VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16)'
cursor_1.executemany(sql, df.values.tolist())

cursor_1.executemany(sql, df.values.tolist())
cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number

想知道我做错了什么。

任何 hep 都会很棒。

【问题讨论】:

  • 你能分享df。不清楚您的数据中有列或行。顺便说一句,数据中有 17 个逗号分隔的元素,但表中有 16 个绑定变量。

标签: python pandas oracle sql-insert cx-oracle


【解决方案1】:

您可以调查几种可能性:

  • 确保所有行的列数相同(通过在调用 execute() 之前打印长度)
  • 通过调用cursor.prepare(sql) 后跟cursor.bindnames() 检查cx_Oracle 认为存在的绑定名称列表

这两项检查都应该有助于发现问题的根源——无论是拼写错误还是“错误”的输入数据。

【讨论】:

    【解决方案2】:

    不清楚您在数据框df 中的内容是列还是行。即使将它们视为列,逗号分隔元素的数量(17)也不符合VALUES 列表中绑定变量的数量(16sql 字符串。

    考虑到从数据框常规插入以及作为列的逗号分隔元素,根据表的列数固定列数,更喜欢使用 df.to_sql 在插入过程中通过使用 sqlalchemy.create_engine 进行连接,例如

    import pandas as pd
    import sqlalchemy as db
    
    engine = db.create_engine('oracle+cx_oracle://un:pwd@dbhost:port/dbname')
    conn = engine.connect()
    
    try:
        df.to_sql('stockstats', con=engine, if_exists='append', index=False )
        engine.execute("SELECT * FROM stockstats").fetchall()
    

    针对 NaN 值引起的问题

    【讨论】:

      猜你喜欢
      • 2013-01-29
      • 2017-09-22
      • 2014-06-17
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多