我正在尝试使用基于日期范围的Python将数据从一个表传输到另一个表。
import anprint
import os
import sys
import re
import datetime
from mydb import cursor
try:
cam_name = sys.argv[1]
rec_date = sys.argv[2]
except:
print "Usage: %s cam_name date " % sys.argv[0]
sys.exit(1)
dbObj = anprint.ExcelDb()
# Get a list of the plates...
tablename = "customer_1.%s_anpr_vega" % cam_name
sql = """SELECT plate, datetime, id FROM %s WHERE DATE(datetime)="%s" """ % (tablename, rec_date)
cursor.execute(sql)
retval = cursor.fetchall()
for values in retval:
print values
(vrm, vrm_datetime, record_id) = values
dbObj.reconcile_plate(cam_name, vrm, vrm_datetime, record_id)
答案 0 :(得分:0)
1)不好的做法:
sql = """SELECT plate, datetime, id FROM %s WHERE DATE(datetime)="%s" """ % (tablename, rec_date)
cursor.execute(sql)
请执行以下操作:
sql = """SELECT plate, datetime, id FROM %s WHERE DATE(datetime)=?""" % tablename
cursor.execute(sql, [rec_date])
2)使用sys.argv[n]
获取命令行参数(如cam_name = sys.argv[1]
)是一种简单而不好的解决方案。好的方法是使用argparse
为脚本分配命令行参数。
3)最好在sql中使用between
运算符,如下所示:
sql = "SELECT plate, datetime, id FROM " +tablename+ " WHERE datetime between ? and ?"
cursor.execute(sql, [start_date, end_date])
此外read it用于理解参数样式SQL查询。