Python: Text file insert to MySQL

Schedule sschedule at gmail.com
Tue Oct 6 20:20:45 CEST 2009


Hello,

I am currenty using MySQL 5.1 community server and trying to import the data
of the comma delimited text file into the table using python 2.6 scripts. I
have installed Mysqldb 1.2.2.

follwoing is my script:




   1. import MySQLdb, csv, sys
   2. conn = MySQLdb.connect (host = "localhost",user = "usr", passwd
= "pass",db = "databasename")
   3. c = conn.cursor()
   4. csv_data=csv.reader(file("a.txt"))
   5. for row in csv_data:
   6. 	print row
   7. 	c.execute("INSERT INTO a (first, last) VALUES (%s, %s), row")
   8. c.commit()
   9. c.close()

import MySQLdb, csv, sys conn = MySQLdb.connect (host = "localhost",user =
"usr", passwd = "pass",db = "databasename") c = conn.cursor()
csv_data=csv.reader(file("a.txt")) for row in csv_data: print row
c.execute("INSERT INTO a (first, last) VALUES (%s, %s), row") c.commit()
c.close()

the contents of the text file eg. :
-----------------
John,Smith
Danie,Thomas
Ronald,Rey
--------------------

When I execute the statement I get the following error:
------------------------------------------------------------------------------------
C:\Python26\lib\site-packages\MySQLdb\__init__.py:34: DeprecationWarning:
the sets module is deprecate
d
from sets import ImmutableSet
['John', 'Smith']
Traceback (most recent call last):
File "e:\Scripts\test.py", line 10, in <module>
c.execute("INSERT INTO a (first, last) VALUES (%s, %s), row")
File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 166, in
execute
self.errorhandler(self, exc, value)
File "C:\Python26\lib\site-packages\MySQLdb\connections.py", line 35, in
defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL
syntax; check the manual tha
t corresponds to your MySQL server version for the right syntax to use near
'%s, %s), row' at line 1")
------------------------------------------------------------------------------------

Any kind of help to get me going will be greatly appreciated.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091006/6c08e85f/attachment.html>


More information about the Python-list mailing list