数据库
首页 > 数据库> > Python / MySQL查询错误:`未知列`

Python / MySQL查询错误:`未知列`

作者:互联网

此脚本用作命令行前端,以将记录添加到本地托管的MySQL数据库.

我收到此错误:

mysql.connector.errors.ProgrammingError:1054(42S22):’字段列表’中的未知列’西瓜’

但西瓜是我想要进入的价值,而不是列名!

这是脚本:

#! /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()

和表架构:

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)

解决方法:

"INSERT INTO fruit (name, variety) VALUES (%s, %s)" % ("watermelon", "melon")

字面上变成了

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

西瓜和甜瓜不是字符串,而是列.要解决此问题,请在%s周围加上引号.

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

但是,您应该将其运行为:

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

请注意,我们删除了%s周围的引号,并将变量作为第二个参数传递给execute方法.执行可以防止从变量中注入sql,也可以在引号中包装字符串.

有关更多信息,请参阅http://mysql-python.sourceforge.net/MySQLdb.html#some-examples

标签:mysql-connector,python,mysql,command-line
来源: https://codeday.me/bug/20190831/1775514.html