[Tutor] Re: Tutor digest, Vol 1 #2152 - 10 msgs
Charlie Clark
charlie@begeistert.org
Wed Jan 1 13:31:01 2003
On 2002-12-31 at 18:00:05 [+0100], tutor@python.org wrote:
> shobhan <schalla@vasoftware.com> wrote:Hi Pythoners,
>
> Can anyone tell me how to connect to Oracle DB using Python and dump the
> data from a table called "logs" into a text file in CSV format..? The
> text file thus created should be of the format (2002-12-30-logs.txt). It
> would be fine if anyone can show a sample script.
>
> Thanks in advance
> Schalla
Hi Schalla,
Az has already basically covered this already but his pseudo-code isn't
really Python.
The DB-API is documented at
http://www.python.org/peps/pep-0249.html
but you might not find that too helpful.
but
http://www.amk.ca/python/writing/DB-API.html
is quite good.
There is a special interest group with mailing list you might want to look
at
http://www.python.org/sigs/db-sig/
Embedding SQL in Python is quite easy once you've got the hang of it.
Before you go any further you will need the appropriate Python driver for
the Oracle database or mxODBC if the database is available via ODBC.
As Az said, you need to connect to the database. I've never heard of this
as a URL, it's called a connection object in Python. You then use your
connection object to do everything for you.
Your actual code will then look a bit like this:
import oracledb # change to use the real driver
f_out =3D open("text_file.csv", "w")
# the next line must be changed
db =3D oracledb.oracledb('the_database', 'schalla', 'secret_word')
cursor =3D db.cursor()
cursor.execute('SELECT * from logs')
while (1):
=09record =3D cursor.fetchone()
=09if not record:
=09=09break # we must have all the records
=09line =3D "|".join(record) # replace "|" with whatever symbol you want to
=09f_out.write(line)
f_out.close()
db.commit()
db.close()
Hope that helps! Seasons greetings from a miserable and wet Germany
Charlie