我可以成功地将整个DataFrame插入到我的Oracle表中,但我无法弄清楚如何将单个变量插入到我的表中。我使用绑定变量和常规Python变量都失败了。
我的变量year
打印出2014
,在这种情况下,因为我的代码解析了我运行它的文档中的年份;并且它最终必须在100个文档上运行。
所以我的SQL语句如下:
cursor = con.cursor()
exported_data = [tuple(x) for x in df_Quota.values]
new_variable = year
sql_query = ("INSERT INTO ROUGHTABLE(species, date_posted, stock_id, pounds, money, sector_name, ask)" "VALUES (:1, :2, :3, :4, :5, 'NEFS 2', '1')")
year_command = ("INSERT INTO ROUGHTABLE(trade_year)" "VALUES (:1)")
cursor.executemany(sql_query, exported_data)
cursor.executemany(year_command, new_variable)
con.commit()
cursor.close()
con.close()
并且失败并显示错误cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number
...当我尝试时它也会失败:
year_command = ("INSERT INTO ROUGHTABLE(trade_year)" "VALUES (year)")
cursor.execute(year_command)
错误cx_Oracle.DatabaseError: ORA-00984: column not allowed here
...
所以我对如何将单个Python变量放入Oracle表格感到困惑。理想情况下,我希望将变量year
的值导出到Oracle表中的列trade_year
。任何帮助解决这个问题将不胜感激。
df_Quota:
AvailableQuota DatePosted ID LiveWeightPounds price
0 GOM COD 5/20 1724 2328 $9,000
1 GOM HADD 5/20 1724 445 $9,000
2 GOM BB 5/20 1724 3007 $9,000
3 GREYSOLE 5/20 1724 850 $9,000
4 DABS 5/20 1724 3101 $9,000
5 GOM YT 5/20 1724 1995 $9,000
6 GBE COD 5/20 1578 538 $1.00
7 GB BB 5/20 1578 1755 $0.20
8 GB YT 5/20 1578 243 $1.00
9 SNE BB 5/20 1578 490 $0.45
10 SNE YT 5/20 1578 153 $0.50
11 GOM BB 5/20 1578 3965 $0.15
12 Whake 5/20 1578 2727 $0.20
13 POLL 5/20 1578 9227 $0.01
14 RED 5/20 1578 15060 $0.01
15 GBE COD 5/20 310 825 15,000
16 GBW COD 5/20 310 9033 15,000
17 DABS 5/20 310 12419 15,000
18 WHAKE 5/20 310 3120 15,000
19 POLL 5/20 310 65234 15,000
20 RED 5/20 310 76610 15,000
21 SNE BB 5/20 310 2121 15,000
22 GOM BB 5/20 310 7285 15,000
答案 0 :(得分:2)
这是一个简单的例子:
import cx_Oracle
import csv,sys
dsnStr = cx_Oracle.makedsn("xxxxxxxxxxxxx", "1521", "xxxxxxxx")
con = cx_Oracle.connect(user="scott", password="tiger", dsn=dsnStr)
print "Database version " + con.version
myCur = con.cursor()
myCur.prepare( 'insert into roughtable( trade_year ) values ( :theYear )' )
myYear='2016'
myCur.execute(None, {'theYear':myYear})
con.commit()
con.close()