对不起,如果这是重复的话;我尝试搜索Google和之前的Stack Overflow问题,但无法找到答案。
连接代码:
import cx_Oracle as o
con = o.connect('**', '**', '**')
con.version
cur = con.cursor()
加载DF的代码:
import pandas as pd
df = pd.read_excel("filename.xlsx")
df有两列,COLUMN1
为7位数字,COLUMN2
为字符串
我有一个名为' MARSHALLTEST
'的Oracle表。使用COLUMN1 number(7)
和COLUMN2 varchar(200)
,我希望INSERT INTO
该表中的相应列。
这给了我一条错误消息:
rows = [tuple(x) for x in df.values]
cur.executemany('''INSERT INTO MARSHALLTEST (COLUMN1, COLUMN2) VALUES (:0,:1)''',rows)
con.commit()
错误讯息:
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
<ipython-input-6-c4f7ad8118fd> in <module>()
1 #statement = 'insert into MARSHALLTEST (OPPORTUNITY_INVOICE) values (df1)'
2 rows = [tuple(x) for x in df.values]
----> 3 cur.executemany('''INSERT INTO MARSHALLTEST ('OPPORTUNITY_INVOICE', 'SF_OPP_ID') VALUES (:0,:1)''',rows)
4 con.commit()
UnicodeEncodeError: 'ascii' codec can't encode character '\u201a' in position 22: ordinal not in range(128)
我也试过这个:
for s in df:
statement = 'insert into MARSHALLTEST (OPPORTUNITY_INVOICE, SF_OPP_ID) values (s)'
cur.execute(statement)
con.commit()
错误讯息:
DatabaseError Traceback (most recent call last)
<ipython-input-15-2c2e69dfd9bf> in <module>()
1 for s in df:
2 statement = 'insert into MARSHALLTEST (OPPORTUNITY_INVOICE, SF_OPP_ID) values (s)'
----> 3 cur.execute(statement)
4 con.commit()
DatabaseError: ORA-00947: not enough values
答案 0 :(得分:0)
您可以使用以下代码将数据框直接保存到表中: 导入cx_Oracle
从sqlalchemy导入类型,create_engine
newconn = create_engine('oracle + cx_oracle:// username:pswd @ host:port /?service_name = xxx')
df.to_sql('testtablex',newconn,if_exists ='replace',index = False)