Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

Python/MySQL query error: `Unknown column`

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.errors.ProgrammingError: 1054 (42S22): Unknown column 'watermelon' in 'field list'

But watermelon is the value I am trying to enter, not the column name!

Here is the script:

#! /usr/bin/python

#use command line as front end to enter new rows into locally hosted mysql database

import mysql.connector

#create inputs
new_fruit = raw_input('What fruit do you want to add? ')
new_fruit_type = raw_input('Which type of ' + new_fruit + '? ')

#connect to dbase
conn = mysql.connector.connect(user='root', password='xxxx', database='play')

#instansiate cursor
cursor = conn.cursor()

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

#execute sql
cursor.execute(add_record)

#close out
conn.commit()
cursor.close()
conn.close()

And the table schema:

mysql> describe fruit;
+---------+----------+------+-----+---------+----------------+
| Field   | Type     | Null | Key | Default | Extra          |
+---------+----------+------+-----+---------+----------------+
| id      | int(11)  | NO   | PRI | NULL    | auto_increment |
| name    | char(30) | YES  |     | NULL    |                |
| variety | char(30) | YES  |     | NULL    |                |
+---------+----------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
question from:https://stackoverflow.com/questions/65932515/how-to-resolve-unknown-column-letters-in-field-list-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
"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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...