2

I have a table where I need to populate email addresses from txt file, date and source from python variables. Down the code, a is the variable am getting from txt and b, c are the python variables I need to insert along

import csv,MySQLdb,os,os.path,datetime as dt
from sys import argv
path = argv
prompt = '>'
filename = raw_input(prompt)
fname = os.path.basename(filename)
source = fname
print "",source
date = dt.datetime.today().strftime("%d/%m/%y")
date_log = date
print "",date_log
db = MySQLdb.connect("localhost","root","passwd","testdb")
x = db.cursor()
csv_data  = csv.reader(file(filename))
for row in csv_data:
    print row
    query = (" INSERT INTO test(a,b,c) VALUES (%s,%s,%s)",row)
    x.execute(query, (date_log, source))
db.commit()
db.close()

Here am getting some error as follows:

File "csv2mysql.py", line 31, in <module>
    x.execute(query, (date_log, source))
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py",line159,in execute
    query = query % db.literal(args)
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'

any help is much appreciated

1
  • query is not fine... checkout the query string... Your query is like something ('INSERT INTO test(a,b,c) VALUES (%s, %s, %s)', (val1, val2,...)) Commented May 25, 2015 at 9:19

1 Answer 1

4

Replace query string

 query = (" INSERT INTO test(a,b,c) VALUES %s") %(row,)

or

 query = (" INSERT INTO test(a,b,c) VALUES %s") % str(row)

Hope it will work for you...

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Dhaval , i changed the query as u said, am getting this error, can u suugest what to do ['[email protected]'] Traceback (most recent call last): File "2csv2mysql.py", line 27, in <module> x.execute(query, (date,fname)) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 159, in execute query = query % db.literal(args) TypeError: not all arguments converted during string formatting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.