Search code examples
pythonmysqlpython-3.xpymysql

Python pymySQL string quotes


I am trying to insert a string

insert_cmd = "INSERT INTO inv values (\""+str(row[1])+"\",\""+str(row[2])+"\")
(cur.execute(insert_cmd))

Error Message:

pymysql.err.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'google search appliance"","active","D\' at line 1')

Solution

  • Better to use query parameters to avoid quoting and other issues:

    cur.execute("INSERT INTO inv values (%s, %s)", (str(row[1]), str(row[2])))
    

    It's also a best practice to name your columns in case your model changes later:

    "INSERT INTO inv (col1, col2) VALUES (%s, %s)"