How to substitute variable to query SQL?

别来无恙 提交于 2021-02-20 02:43:50

问题


I have the following query line:

c.execute("""insert into apps (url)""")

I have variable url that I try to append in query insert.

But U get Mysql sintax error

There are two field in table: id - autoincrement and url


回答1:


The better question should be "How to substitute value in string?" as the query you are passing to the c.execute() is of the string format. Even better, "How to dynamically format the content of the string?"

In python, to do that there are many ways:

  1. Using str.format()

    # Way 1: Without key to format
    >>> my_string = "This is my {}"
    >>> my_string.format('stackoverflow.com')
    'This is my stackoverflow.com'
    
    # Way 2:  with using key
    >>> my_string = "This is my {url}"
    >>> my_string.format(url='stackoverflow.com')
    'This is my stackoverflow.com'
    
  2. Using string formater %s as:

    # Way 3: without key to %s
    >>> my_string = "This is my %s"
    >>> my_string % 'stackoverflow.com'
    'This is my stackoverflow.com'
    
    # Way 4: with key to %s
    >>> my_string = "This is my %(url)s"
    >>> my_string % {'url': 'stackoverflow.com'}
    'This is my stackoverflow.com'
    

For specific to SQL query, the better way is to pass value like:

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

in order to prevent possible SQL Injection attacks



来源:https://stackoverflow.com/questions/40679501/how-to-substitute-variable-to-query-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!