A good way to escape quotes in a database query string?

后端 未结 9 1231
暖寄归人
暖寄归人 2020-12-09 07:49

I\'ve tried all manner of Python modules and they either escape too much or in the wrong way. What\'s the best way you\'ve found to escape quotes (\", \') in Python?

相关标签:
9条回答
  • 2020-12-09 08:15

    Use json.dumps.

    >>> import json
    >>> print json.dumps('a"bc')
    "a\"bc"
    
    0 讨论(0)
  • 2020-12-09 08:20

    Triple single quotes will conveniently encapsulate the single quotes often used in SQL queries:

    c.execute('''SELECT sval FROM sdat WHERE instime > NOW() - INTERVAL '1 days' ORDER BY instime ASC''')
    
    0 讨论(0)
  • 2020-12-09 08:20

    Triple-double quotes are best for escaping:

    string = """This will span across 'single quotes', "double quotes",
    and literal EOLs all in the same string."""
    0 讨论(0)
  • 2020-12-09 08:23

    For my use case, I was saving a paragraph against the database and somewhere in the paragraph there might have been some text with a single quote (example: Charlie's apple sauce was soggy)

    I found this to work best:

    database_cursor.execute('''INSERT INTO books.collection (book_name, book_quoted_text) VALUES ('%s', "%s")''' % (book_name, page_text.strip()))
    

    You'll notice that I use "" after wrapping the INSERT statement in '''

    0 讨论(0)
  • 2020-12-09 08:27

    If it's part of a Database query you should be able to use a Parameterized SQL Statement.

    As well as escaping your quotes, this will deal with all special characters and will protect you from SQL injection attacks.

    0 讨论(0)
  • 2020-12-09 08:27

    If you're using psycopg2 that has a method for escaping strings: psycopg2.extensions.adapt() See How to quote a string value explicitly (Python DB API/Psycopg2) for the full answer

    0 讨论(0)
提交回复
热议问题