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)
Literally becomes
Instead of strings,
watermelon
andmelon
are columns. To fix this, put quotes around your%s
.However, you should run it as:
Notice we took away the quotations around the
%s
and are passing the variables as the second argument to theexecute
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
The issue is here:
Imagine the query this would produce:
Those values aren't values anymore! They look more like column references (
Unknown column 'watermelon' in 'field list'
)Instead, you should use prepared statements:
This will automatically take care of the parameterization for you, and will prevent SQL Injection