如何使用参数搜索字符串

时间:2013-06-15 15:44:51

标签: python mysql

我试图将查询传递给mysql数据库 这是代码

#!/usr/bin/python
import sys

sql = "select count(distinct offering),count(learner),count(distinct learner),sum(transaction ) from EMS_data where offering like 'engineering'  and manager='patel' and fiscal like %s" % sys.argv[1]

在我输入的财政栏目中 2010 2011 2012 2013

在命令行中我输入了文件名和2013.但它显示了我的结果

mysql_exceptions.OperationalError: (1054, "Unknown column '2013' in 'where clause'")

我没有搜索列,但包含在列中。

1 个答案:

答案 0 :(得分:0)

我建议使用MySQLdb's prepared statements,如下所示:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'test623', 'testdb')

with con:    

    cur = con.cursor()

    cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s", 
        ("Guy de Maupasant", "4"))        

    print "Number of rows updated:",  cur.rowcount

但是,您的直接问题可以通过以下方式解决:

sql = "select count(distinct offering),count(learner),count(distinct learner),sum(transaction ) from EMS_data where offering like 'engineering'  and manager='patel' and fiscal regexp '%s'" % sys.argv[1]