Search code examples
pythonsqlquotes

Python: inserting double or single quotes around a string


Im using python to access a MySQL database and im getting a unknown column in field due to quotes not being around the variable.

code below:

cur = x.cnx.cursor()
cur.execute('insert into tempPDBcode (PDBcode) values (%s);' % (s)) 
rows = cur.fetchall()

How do i manually insert double or single quotes around the value of s? I've trying using str() and manually concatenating quotes around s but it still doesn't work. The sql statement works fine iv double and triple check my sql query.


Solution

  • You shouldn't use Python's string functions to build the SQL statement. You run the risk of leaving an SQL injection vulnerability. You should do this instead:

    cur.execute('insert into tempPDBcode (PDBcode) values (%s);', s) 
    

    Note the comma.