Python MySQL OperationalError: (1054, "Unknown column 'XX' in 'where clause'")

问题症状和这里的类似,直接在SQL语句用%拼接string会出现

OperationalError: (1054, "Unknown column 'XX' in 'where clause'")错误,使用2.6+版本的Python最好使用format方法,如下:

SQL语句:

run_sql.sql:

create database name;

create table just_id_and_name (
    id integer primary key auto_increment,
    name varchar(200) not null
);

use name;

insert into just_id_and_name (name) values ('Jerry');
insert into just_id_and_name (name) values ('Jim');
insert into just_id_and_name (name) values ('Tom');
insert into just_id_and_name (name) values ('Lee');

使用Python连接实例:

import MySQLdb

conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='', db="name")
cur = conn.cursor()
data = 'Tom'
query = "select * from just_id_and_name where name = '{0}'".format(data)
print query
cur.execute(query)
res = cur.fetchone()
print res

这样就不会出错了。

原文地址:https://www.cnblogs.com/jaw-crusher/p/3594541.html