0
我不想負擔的人我的整個代碼, 所以我要去嘗試,只得到部分,可以幫助回答我的問題傳遞變量到MySQL查詢
我需要添加日期範圍爲輸入到我的蟒蛇呼叫
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()
太好了,生病了,非常感謝你 – user2333346