[Tutor] Handling MySQLdb exceptions
Paul Schewietzek
tetsuo2k6 at web.de
Wed Dec 19 19:14:40 CET 2007
Hi there!
I'm writing a script that inserts data from a .csv file into a
MySQL-Database.
Actually, it works fine (the data make it into the database correctly),
however everytime it runs it raises an exception coming from the
MySQLdb-module.
Here's the code:
--------------------------------------------------------------
#!/usr/bin/env python
import MySQLdb
import sys
if len(sys.argv) <> 2:
print("""Usage: put_data_into_pool <well formatted .csv-file>
Columns need to be:
title, firstname, lastname, street, number of
house, postal code, city, phone number""")
sys.exit(0)
tabelle = open(sys.argv[1], "r")
db = MySQLdb.connect(host="localhost", user="user", passwd="xxxxxxxx",
db="db")
cursor = MySQLdb.cursors.Cursor(db)
line = tabelle.readline()
while line <> "":
# try:
cursor.execute('INSERT INTO pool (titel, vorname,
nachname, strasse, hausnummer, plz, ort, rufnummer, datum) VALUES (' +
line + ');')
line = tabelle.readline()
# except(_mysql_exceptions.OperationalError):
# pass
tabelle.close()
------------------------------------------------------------------
The exception goes like this:
------------------------------------------------------------------
Traceback (most recent call last):
File "bin/auftragserfassung/put_data_into_pool.py", line 22, in <module>
cursor.execute('INSERT INTO pool (titel, vorname, nachname,
strasse, hausnummer, plz, ort, rufnummer, datum) VALUES (' + line + ');')
File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line
166, in execute
self.errorhandler(self, exc, value)
File "/var/lib/python-support/python2.5/MySQLdb/connections.py", line
35, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1136, "Column count doesn't match
value count at row 1")
-------------------------------------------------------------------
Is there any way to handle this exception? As you can see, I already
tried it with _mysql_exceptions.OperationalError (the lines that are
commented out), but _mysql_exceptions is not defined to Python....
Just so you don't need to wonder: The .csv-file I give to the script for
testing is absolutely OK.
On a side note, would you think I should post this somewhere else? If
so, where?
Any help is appreciated - I'll answer tomorrow (have to go now).
Kindest regards, Paul
More information about the Tutor
mailing list