python查询mysql结果输出到文件

#/usr/bin/python
import os
import datetime
import time
import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding('utf8')  
if __name__ == "__main__":
	t = datetime.datetime.now()
	print "begin:" ,t
	if len(sys.argv) > 1:
		print sys.argv[1]
		str_time = sys.argv[1]
	else:
		y=t.year
		m=t.month
		d=t.day
		str_time=str(y)+"-"+str(m)+"-"+str(d)
	print str_time
	db = MySQLdb.connect(host='localhost',user='root',passwd='xxxxxx', port=3306, db='dbname',charset='utf8')	
	try:
		db_cursor = db.cursor()
		db_cursor.execute('select datatime, car_brand from source_link')
		rows = db_cursor.fetchall()
		with open('record.txt', 'w') as fout:
			#print >>fout, rows	
			for row in rows:
				t = row[0].strftime('%Y-%m-%d %H:%M:%S.%f')
				fout.write('%s,%s\n'%(t,row[1]))
		db_cursor.close()
	except Exception,e:
		print e
	finally:
		db.close()

猜你喜欢

转载自blog.csdn.net/xueruixuan/article/details/80236543