0

I am trying to insert data into my SQL table via Python.

My code is:

sql = "INERT INTO TABLE VALUES" + str(tuple(row))
cursor.execute(sql)

The issue I have is that I am getting syntax errors on words such as table's due to the apostrophe.

I cannot use:

replace('\'','\'\'') 

on the str because that would change the whole SQL insert.

Is it possible to insert the row data of each element inside a tuple to eliminate this issue?

4
  • 1
    You can use insert with parameters, as explained in this post, or here. That will escape the special characters for you. Commented Apr 5, 2021 at 20:23
  • Doesn't seem to be working for some strange reason. sql = ''' INSERT INTO TABLE VALUES ('?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')''' args = tuple(row) cursor.execute(sql, args) I keep getting the error: pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 11 parameters were supplied', 'HY000') Commented Apr 5, 2021 at 20:44
  • 2
    Don't believe you enclose question mark markers in their own apostrophes. You should also provide the list of table columns: INSERT INTO table_name (column_list) VALUES (?, ?, ...) Commented Apr 5, 2021 at 21:04
  • that worked, thanks!! Commented Apr 6, 2021 at 19:22

0

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.