我不想用我的整个代码给人们带来负担,所以我将尝试只获取可以帮助回答我的问题的部分
我需要添加一个日期范围作为我的 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()