【问题标题】:How do I insert a dataframe to an oracle table illegal/variable oracle如何将数据框插入到 oracle 表非法/变量 oracle
【发布时间】:2021-02-12 05:39:59
【问题描述】:

我有以下数据框

df2 = {names: [PEPE, LUIS], id: [1,2], stages: [0,1], ord: [3, 2]}

但这些是必填字段,要插入的表,您有更多字段,允许为空。

数据框在哪里等价于表中的这些字段

df2 = {labels= :1, id= :2, stages= :3, ord= :4}

桌子

CREATE TABLE customer_prf
(
  names      VARCHAR2(80) NOT NULL, 
  label      VARCHAR2(80) NOT NULL,
  type       VARCHAR2(80) NOT NULL,
  type_flag  INT,
  type_flag2 INT,
  conc       VARCHAR2(80), 
  id         INT NOT NULL,
  n_stage    INT NOT NULL,
  ctry       INT NOT NULL,
  "order"    INT NOT NULL
);

您是如何设法从数据中插入数据的,其中插入的值已经在查询字符串中预先定义,我做错了,ora-01036 发送给我。此外,id 的值会自动增加吗?

我的代码

import cx_Oracle
import pandas as pd

...
df2.to_dict(orient='records')
print(df2)

conn = cx_Oracle.connect(connection)
cur = conn.cursor()
id = 0
insert_qry = cur.execute("insert into customer_prf values(
'references',
:1,
'text',
'',
'',
:2,
:3,
2,
:4)"
   cursor.prepare(insert)

你会如何插入它

【问题讨论】:

  • 您的insert_qry 字符串格式不正确。字符串中不应有返回 (\n)。
  • 我如何在该必填字段中输入值?因为在插入定义的值时,它在脚本中带有一个字符串
  • 删除字符串中的所有返回。这一切都需要在一条线上。
  • 明白了,非常感谢,如何设置id字段?变量中的可递增?

标签: python pandas dataframe oracle11g cx-oracle


【解决方案1】:

您可以使用df2.values.tolist 来获取参数列表,并使用如下代码在数据框中插入值:

import pandas as pd
import cx_Oracle
conn = cx_Oracle.connect('un/pwd@host:port/dbname')

try:
    cursor = conn.cursor()
    df2 = pd.DataFrame({'names':['Pepe','Luis'], 'stages': [0,1], 'order': [3, 2]}) 
    col_list = df2.values.tolist()

    cursor.prepare("INSERT INTO customer_prf(names,label,type,id,n_stage,ctry,\"order\") VALUES(:1,'references','text',seq_customer.nextval,:2,2,:3)")
    cursor.executemany(None,col_list)
    print("executed!")
except Exception as err:
    print('Error', err)
else:
    conn.commit()

在哪里

  • 更喜欢使用executemany 而不是execute 高性能

  • 创建一个序列 (seq_customer) 并添加到您的值列表 (seq_customer.nextval) 使用 DB 版本 11g,如果您的数据库版本为 12c+,则 ID 列可以在 create table ddl 语句中标识(例如。在创建表期间)例如

    ID INT generated always as identity primary key

【讨论】:

  • 我明白了,非常感谢,如何设置id字段?变量中的可递增?
  • 哦,好吧,我错过了@Jonathan 的那部分。只需创建一个序列 (seq_customer) 并添加到您的值列表 (seq_customer.nextval),就像使用 DB 版本 11g。
  • 我故意将 DEFAULT 'references' 保留在创建语句中,因为您不需要将其作为文字放在应用程序中。请先尝试使用这五列,然后您可以逐渐将其余列添加到数据库中,以免@Jonathan在这里出现混乱。此外,您建议的编辑将需要数据框的其余部分。
  • 对不起,我会带走,碰巧id字段不是主要的,所以从数据框中生成该字段,因为最后它只是一个连续的,然后有字段是强制性的,其他是必要的,但其他不是,我不知道如何插入并发送给我非法/变量
  • 我进行了编辑,以便获得一个完整的案例,其中包含表 @Jonathan 的所有列。顺便说一句,您可以恢复您的编辑除了 CREATE TABLE 语句,以便该问题的未来读者可以轻松理解问题和答案的相关性。
猜你喜欢
  • 2015-02-16
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 2020-10-29
  • 2017-09-30
  • 1970-01-01
  • 2011-07-07
  • 2017-02-18
相关资源
最近更新 更多