Search code examples
python-3.xpymysql

Can't query data using flask framework pymysql


Under the python flask framework, data cannot be queried using pymysql:

def sql_query (commit_ip):
    with db.cursor() as cursor:
        sql = "select client_ip, result, date_time from ipset where client_ip = 'commit_ip'"
        cursor.execute (sql)
        dict_ipset = cursor.fetchall ()
        return dict_ipset

The variable commit_ip can be queried only after it is replaced with a specific IP. The same is true for date_time. The data type of client_ip is char (15). How should this sql be written?


Solution

  • You should pass variable values as a tuple as second parameter to execute. Example from PyMySql's doc:

        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
    

    So for you it would be:

        sql = "select client_ip, result, date_time from ipset where client_ip = %s"
        cursor.execute(sql, (commit_ip,))