问题
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:
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'
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