1

I am trying to insert a value into my local MySQL instance using Python but I keep getting an error

Here is my code:

con = mdb.connect('localhost', 'root', 'password', 'testDB')
cur = con.cursor()
cur.execute('''INSERT INTO testDB.testPython VALUES (%s)''',("HelloWorld"))
con.commit()

but I am getting the following error

TypeError: not all arguments converted during string formatting

Does anyone know why?

0

2 Answers 2

3

TypeError is a basic Python error:

Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

Your trouble is you forgot to place a comma in your tuple, and without it is considered as the object in parenthesis: your single string.

Explanation with interpreter:

In [1]: ('Hello')
Out[1]: 'Hello'
In [2]: ('Hello',)
Out[2]: ('Hello',)

Fix like this to resolve your trouble :

cur.execute('INSERT INTO testDB.testPython VALUES (%s)', ("HelloWorld",))
Sign up to request clarification or add additional context in comments.

Comments

0

Don't use the triple quotes, this will treat your sql includ the parameter as a string literal. Use the standard quote ( " ) instead.

3 Comments

But... standard quotes make string literals as well.
Maybe I make a mistake, but there is no difference between simple and double quote in Python: docs.python.org/2.0/ref/strings.html and stackoverflow.com/questions/56011/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.