0

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

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Goga
  • 405
  • 1
  • 6
  • 13

1 Answers1

3

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

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126