从命令行将变量传递给MYSQL查询

时间:2013-08-19 22:50:04

标签: mysql-python

我不想用我的整个代码给人们带来负担, 因此,我将尝试仅获取有助于回答我的问题的部分

我需要添加日期范围作为我的python调用的输入

python query2.py -v --start_date='2013-08-12' --finish_date='2013-08-15' > output.txt

但是当我尝试将此作为连接字符串添加到查询子例程中的SQL_QUERY变量时,我收到此错误:

    SQL_QUERY += """ HAVING sm.created >= '2013-08-12' and sm.created <= '2013-0
8-15' """
UnboundLocalError: local variable 'SQL_QUERY' referenced before assignment
Killed by signal 2.

所以我猜我不能以这种方式添加变量,

SQL_QUERY += " HAVING sm.created >= " + options.db_start + " and sm.created <= " + options.db_finish

有人能告诉我什么错吗?

由于

import sys
import os
import time
import optparse
import getpass
import subprocess
from contextlib import contextmanager
import MySQLdb


# TODO: modify this with columns, course_id that make sense for you
SQL_QUERY = """
select au.email, sm.created, sce.created , sm.grade, sm.max_grade
from auth_user au, courseware_studentmodule sm,  student_courseenrollment sce
where sm.student_id = au.id and sm.student_id = sce.id
and sm.course_id = 'MyCourse'
and sm.module_type = 'problem' 
"""

def query():
    """

    SQL_QUERY += " HAVING sm.created >= " + options.db_start + " and sm.created <= " + options.db_finish
    log_info("query = %s" % SQL_QUERY)
    result = None
    conn = None
    try:
        conn = MySQLdb.connect(host='127.0.0.1', 
                port=options.local_port,
                user=options.db_user, 
                passwd=options.db_password, 
                db=options.db_name);
        cur = conn.cursor()
        cur.execute(SQL_QUERY)
        result = cur.fetchall()
    except MySQLdb.Error as e:
        sys.stderr.write("Database error %d: %s\n" % (e.args[0],e.args[1]))
    if conn:
        conn.close()
    return result


def parse_command_line():
    usage = """usage: %prog [options]

 parser.add_option("--start_date", dest="db_start", 
        help="Database host (default=\"%s\"" % DEFAULT_DB_HOST)
    parser.add_option("--finish_date", dest="db_finish", 
        help="Database host (default=\"%s\"" % DEFAULT_DB_HOST)
    global options
    (options, args) = parser.parse_args()

1 个答案:

答案 0 :(得分:0)

query()功能中,您必须先使用global SQL_QUERY。这里发生的是Python假定在函数内的任何位置分配的任何名称都是该函数的本地名称,除非另有明确说明。如果它只是从名称读取,并且名称在本地不存在,它将尝试在任何包含范围中查找名称(例如模块的全局范围)。