Python String Formats with SQL Wildcards and LIKE

后端 未结 6 895
情深已故
情深已故 2020-11-30 11:04

I\'m having a hard time getting some sql in python to correctly go through MySQLdb. It\'s pythons string formatting that is killing me.

My sql statement is using the

相关标签:
6条回答
  • 2020-11-30 11:30

    We could try escaping the percentage character by doubling them like this:

    query_to_get_user_name = """ 
    SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag 
    ON user.id = tag.userId 
    WHERE user.username LIKE '%%%s%%' """ % (user_name,) 
    
    cursor.execute(query_to_get_user_name)
    
    0 讨论(0)
  • 2020-11-30 11:37

    I have a solution to your problem :

    You can not use :

    "SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username LIKE '%%s%'" % (query)
    

    you can change it with string template, such as :

    import MySQLdb
    import string # string module
    .......
    value = {'user':'your value'}
    sql_template = string.Template("""
    SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN
    tag ON user.id = tag.userId WHERE user.username LIKE '%$user%'
    """)
    
    sql = sql_template.substitute(value)
    
    try:
        cursor.execute(sql)
        ...........
    except:
        ...........
    finally :
       db.close()
    
    0 讨论(0)
  • 2020-11-30 11:38

    Those queries all appear to be vulnerable to SQL injection attacks.

    Try something like this instead:

    curs.execute("""SELECT tag.userId, count(user.id) as totalRows 
                      FROM user 
                INNER JOIN tag ON user.id = tag.userId 
                     WHERE user.username LIKE %s""", ('%' + query + '%',))
    

    Where there are two arguments being passed to execute().

    0 讨论(0)
  • 2020-11-30 11:40
    import mysql.connector
    mydatabase = mysql.connector.connect(host="localhost", user="root", passwd="1234", database="databaseName")
    mycursor = mydatabase.cursor()
    user_input =[]
    item = str("s%")
    user_input.append(item)
    mycursor.execute("SELECT * FROM employees WHERE FIRST_NAME LIKE %s ESCAPE ''",user_input )
    result = mycursor.fetchall()
    for row in enumerate(result):
        print(row)
    
    0 讨论(0)
  • 2020-11-30 11:49

    It's not about string formatting but the problem is how queries should be executed according to db operations requirements in Python (PEP 249)

    try something like this:

    sql = "SELECT column FROM table WHERE col1=%s AND col2=%s" 
    params = (col1_value, col2_value)
    cursor.execute(sql, params)
    

    here are some examples for psycog2 where you have some explanations that should also be valid for mysql (mysqldb also follows PEP249 dba api guidance 2.0: here are examples for mysqldb)

    0 讨论(0)
  • 2020-11-30 11:51

    To escape ampersands in Python string formatting expressions, double the ampersand:

    '%%%s%%' % search_string
    

    Edit: But I definitely agree with another answer. Direct string substitution in SQL queries is almost always a bad idea.

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