Python String Formats with SQL Wildcards and LIKE

后端 未结 6 910
情深已故
情深已故 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: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()
    

提交回复
热议问题