保存一个例子。使用MySQLdb库去连接MySQL数据库。
import MySQLdb #创建连接 conn=MySQLdb.connect(host=db_url,port=db_port,user=db_user,passwd=db_pwd,db=db_name) cur=conn.cursor() try: #加入临时变量" cur.execute('SET @begin_date=\''+begin_time.strftime("%Y-%m-%d")+'\';') conn.commit(); cur.execute('SET @end_date=\''+end_time.strftime("%Y-%m-%d")+'\';') conn.commit(); #执行查询 cur.execute("SELECT t.account_id,t.date,t.site_platform_location,SUM(t.click_pv),SUM(t.show_pv),SUM(t.total_price) FROM atr_stats_planitem_detail t WHERE t.account_id IN ("+",".join(accounts. keys())+") AND (t.date>=@begin_date AND t.date<=@end_date) GROUP BY t.account_id,t.date,t.site_platform_location;") #获取结果 results=cur.fetchall() query_length=len(results) query_result={} for row in results: #按序号获取一行的各列内容 account_id=str(row[0]) datestr=str(row[1]) recscene=str(row[2]) click_pv=str(row[3]) show_pv=str(row[4]) total_price=str(row[5]) recscene_results={} daily_recscene_result=() if not query_results.has_key(account_id): query_result={} else: query_result=query_results[account_id] if query_result.has_key(recscene): recscene_results=query_result[recscene] daily_recscene_result=(click_pv,show_pv,total_price) recscene_results[datestr]=daily_recscene_result query_result[recscene]=recscene_results query_results[account_id]=query_result except BaseException,e: print e #确保数据不会生成 sys.exit(1) finally: conn.close()