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?

Zulu
  • 8,765
  • 9
  • 49
  • 56
cmlakhan
  • 127
  • 1
  • 7

2 Answers2

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",))
Zulu
  • 8,765
  • 9
  • 49
  • 56
0

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

harvey
  • 2,945
  • 9
  • 10
  • 1
    He make as in MySQLdb doc: http://mysql-python.sourceforge.net/MySQLdb.html#some-examples – Zulu Oct 22 '14 at 22:29
  • 2
    But... standard quotes make string literals as well. – Waleed Khan Oct 22 '14 at 22:31
  • 1
    Maybe I make a mistake, but there is no difference between simple and double quote in Python: https://docs.python.org/2.0/ref/strings.html and http://stackoverflow.com/questions/56011/single-quotes-vs-double-quotes-in-python – Zulu Oct 22 '14 at 22:37