2

I'm opening a text file and trying to write it to an SQL database.

import mysql.connector
import sys
import mysql

f = open('norepeats.txt', 'r')

def sniffertodatabase(f):
for line in f:
    linestrip = line.strip()
    IP = linestrip
    cnx = mysql.connector.connect(user='', password='', host='localhost', database='snifferdb')
    cur = cnx.cursor()
    #print IP
    insert_stmt = (
    "INSERT INTO SNIFFERDBIPs (IP)"
    "VALUES (%s)"
    )
    data = ('IP')
    cur.execute(insert_stmt, data)

    #cur.execute("INSERT INTO SNIFFERDBIPs (IP)" "VALUES (%s), (IP)")
    #cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar'))
    cnx.commit()
    cnx.close()
sniffertodatabase(f)

and the error I'm getting is:

Traceback (most recent call last):
File "snifferdatabase.py", line 26, in <module>
  sniffertodatabase(f)
File "snifferdatabase.py", line 19, in sniffertodatabase
  cur.execute(insert_stmt, data)
File "build/bdist.linux-x86_64/egg/mysql/connector/cursor.py", line 480, in execute
mysql.connector.errors.ProgrammingError: Wrong number of arguments during string formatting 

How do I solve this error?

2
  • your data should be ('IP',); it's str now, but you need tuple Commented Nov 21, 2014 at 1:08
  • I didn't post as an answer, so that's ok; by the way, you're creating and closing a connection for every line in your file, you should do it only once, which would be better Commented Nov 21, 2014 at 1:42

2 Answers 2

6

You have data=('IP'). Even though you put it in brackets it is not treated as a tuple. See this:

>>> type(('IP'))
<type 'str'>
>>> type(('IP',))
<type 'tuple'>
>>>

So you need to change your data=('IP') to data=('IP',)

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

Comments

0

You can also use a list instead of a tuple that way you can do

data = ['IP']

Comments

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.