Recently, there are too many situations that need to guide data. It's a little inefficient and troublesome to use the navicat tool on the springboard (because the springboard can't connect to the external network, the exported data files have to be transferred to the local computer through sftp)
anyway, it's better to write a script. Previously, I wrote a shell script to do a timed export task. Now try writing it down in python.
The main libraries used are:
pymysql -- No need to say more about connecting to a database
OS & sys -- possibly back to working directories or external references
xlwt--Writing excel
Here's the code. Overall, it's quite simple. We mainly encounter a character encoding problem, which can be solved by changing it to utf-8.
There's another problem that hasn't been solved: the result of select has no field name, so.... I added the field in the first line of the file manually =. =.
#!/usr/bin/python # -*- coding: cp936 -*- # security: Sensitive database-related parameters are best passed in as parameters rather than scripts import pymysql import xlwt import os,sys def dbConnect(dburl): db_user = sys.argv[1] db_pass = sys.argv[2] db_name = raw_input("The database to be used:") db_conn = pymysql.connect(dburl,db_user, db_pass, db_name)# db_name parameter failed? Coding problem "?" return db_conn def sqlOpt(opt): db_conn = dbConnect("localhost") cur = db.cursor() cur.execute(opt) data = cur.fetchall() db_conn.close() return data def write_to_excel(content): os.chdir("/home/appuser/export_mysql_data/") filename = raw_input("Please enter the file name to be saved,No suffix required:") + '.xls' wbk = xlwt.Workbook(encoding='utf-8') test = wbk.add_sheet('test',cell_overwrite_ok=True) # How to get column names fileds = [u'ID',u'name',u'sex',u'birth',u'department',u'address'] trans_data = list(content) # Write column names for filed in range(0,len(fileds)): test.write(0,filed,fileds[filed]) for row in range(1,len(trans_data)+1): for col in range(0,len(fileds)): test.write(row,col,str(trans_data[row-1][col])) wbk.save(filename) def run_Task(): sql = raw_input("Please input sql Query statement:") result = sqlOpt(sql) write_to_excel(result) run_Task()