使用Python把数据库中数据导出到CSV文件

需要安装两个库pymysql和csv

pip install pymysql csv

代码示例如下:

import pymysql
import csv

import sys
reload(sys)
sys.setdefaultencoding('utf8')

def from_mysql_get_all_info():
    conn = pymysql.connect(
            host='mysql.dba.zuocheng.net',
            port=13306,
            user='root',
            db='test_db',
            password='test_pw',
            charset='utf8')
    cursor = conn.cursor()
    sql = "select * from test_table"
    cursor.execute(sql)
    data = cursor.fetchall()
    conn.close()
    return data

def write_csv():
    data = from_mysql_get_all_info()
    filename = 'data_full.csv'
    with open(filename,mode='w') as f:
        write = csv.writer(f,dialect='excel')
        for item in data:
            write.writerow(item)

write_csv()