Python/MySQL query error: `Unknown column`

后端 未结 2 915
暗喜
暗喜 2021-01-12 19:34

This script is meant to act as a command-line front-end to add records to a locally hosted MySQL database.

I am getting this error:

mysql.connector.err

相关标签:
2条回答
  • 2021-01-12 19:55

    The issue is here:

    add_record = "INSERT INTO fruit (name, variety) VALUES (%s, %s)" % (new_fruit, new_fruit_type)
    

    Imagine the query this would produce:

    INSERT INTO fruit (name, variety) VALUES (watermelon, something_else)
    

    Those values aren't values anymore! They look more like column references (Unknown column 'watermelon' in 'field list')

    Instead, you should use prepared statements:

    query = "INSERT INTO fruit (name, variety) VALUES (%s, %s)"
    cursor.execute(query, (new_fruit, new_fruit_type))
    

    This will automatically take care of the parameterization for you, and will prevent SQL Injection

    0 讨论(0)
  • 2021-01-12 20:07
    "INSERT INTO fruit (name, variety) VALUES (%s, %s)" % ("watermelon", "melon")
    

    Literally becomes

    INSERT INTO fruit (name, variety) VALUES (watermelon, melon)
    

    Instead of strings, watermelon and melon are columns. To fix this, put quotes around your %s.

    "INSERT INTO fruit (name, variety) VALUES ('%s', '%s')" % (new_fruit, new_fruit_type)
    

    However, you should run it as:

    cursor.execute("INSERT INTO fruit (name, variety) VALUES (%s, %s)", (new_fruit, new_fruit_type));
    

    Notice we took away the quotations around the %s and are passing the variables as the second argument to the execute method. Execute prevents sql injection from the variables as well as wraps strings in quotation marks.

    For more information, see http://mysql-python.sourceforge.net/MySQLdb.html#some-examples

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