链接sql数据库并输出csv文件
__author__ = 'chunyang.wu' #作者:SelectDB # -*- coding: utf-8 -*- import MySQLdb import os os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' import sys reload(sys) sys.setdefaultencoding('utf-8') import csv class Handle(): def __init_db(self): self._mysql_db = MySQLdb.connect(host="172.16.1.55",user="test",passwd="123456",port=3306,db="test",unix_socket="/tmp/mysql5.sock") self.mysql_cur=self._mysql_db.cursor() self.seq = 0 def __init__(self): self.__init_db() def _release_db(self): self.mysql_cur.close() self._mysql_db.close() def _do(self): self.mysql_cur.arraysize = 50 select_sql = "SELECT id,email,FROM_UNIXTIME(create_time) AS create_time FROM test.tbl_member " print select_sql self.mysql_cur.execute(select_sql) count = 0 csvfile = file('all_user.csv', 'wb') print dir(csv) writers = csv.writer(csvfile) writers.writerow(['uid', 'email', 'createtime']) while 1: lines = self.mysql_cur.fetchmany(50) if len(lines)==0: break for i in lines: print i writers.writerows([i]) csvfile.close() def main(): p = Handle() p._do() p._release_db() if __name__=="__main__": main()
无语言基础,自学python所做的各种笔记,欢迎大牛指点.