How to export parsed data from Python to an Oracle

2019-09-05 19:44发布

问题:

I have used Python to parse a txt file for specific information (dates, $ amounts, lbs, etc) and now I want to export that data to an Oracle table that I made in SQL Developer.

I have successfully connected Python to Oracle with the cx_Oracle module, but I am struggling to export or even print any data to my database from Python.

I am not proficient at using SQL, I know of simple queries and that's about it. I have explored the Oracle docs and haven't found straightforward export commands. When exporting data to an Oracle table via Python is it Python code I am going to be using or SQL code? Is it the same as importing a CSV file, for example?

I would like to understand how to write to an Oracle table from Python; I need to parse and export a very large amount of data so this won't be a one time export/import. I would also ideally like to have a way to preview my import to ensure it aligns correctly with my already created Oracle table, or if a simple undo action exists that would suffice.

If my problem is unclear I am more than happy to clarify it. Thanks for all help.

My code so far:

import cx_Oracle

dsnStr = cx_Oracle.makedsn("sole.wh.whoi.edu", "1526", "sole")

con = cx_Oracle.connect(user="myusername", password="mypassword", dsn=dsnStr)
print (con.version)

#imp 'Book1.csv' [this didn't work]

cursor = con.cursor()
print (cursor)

con.close()

回答1:

From Import a CSV file into Oracle using CX_Oracle & Python 2.7 you can see overall plan. So if you already parsed data into csv you can easily do it like:

import cx_Oracle
import csv

dsnStr = cx_Oracle.makedsn("sole.wh.whoi.edu", "1526", "sole")

con = cx_Oracle.connect(user="myusername", password="mypassword",     dsn=dsnStr)
print (con.version)

#imp 'Book1.csv' [this didn't work]

cursor = con.cursor()
print (cursor)

text_sql = '''
INSERT INTO tablename (firstfield, secondfield) VALUES(:1,:2)
'''

my_file = 'C:\CSVData\Book1.csv'
cr = csv.reader(open(my_file,"rb"))
for row in cr:    
    print row
    cursor.execute(text_sql, row)
    print 'Imported'
con.close()