Contents

Python-第三方库-Mysql

PYPI官网

mysql文档

连接数据库

1
2
3
4
5
6
db = mysql.connector.connect(
        host="xxx",
        database="xxx",
        user="xxx",
        password="xxx"
)

执行命令并获取结果

1
2
3
cursor = db.cursor()
cursor.execute("SELECT idc_name, module_id from collector_deploy")
idcModule = cursor.fetchall()

mysql数据写入csv文件

[CSDN daiyu__zz python将mysql数据导出到csv文本]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import pymysql
import csv

def from_mysql_get_all_info():
    conn = pymysql.connect(
        host='xxxxxx',
        port=3306,
        user='xxxx',
        db=xx',
        password='xxxxx',
        charset='utf8mb4'
    cursor = conn.cursor()
    sql = 'select * from py.tencent_news'
    cursor.execute(sql.encode('utf-8'))
    data = cursor.fetchall()
    conn.close()
    return data


def write_csv():
    data = from_mysql_get_all_info()
    filename = 'data/corpus.csv'
    with open(filename,mode='w',encoding='utf-8') as f:
        write = csv.writer(f,dialect='excel')
        for item in data:
            write.writerow(item)

write_csv()

当表很大的时候通过fetchone()来优化逻辑,每次取一条数据,通过判断row是否为None来判断是否结束

1
2
3
4
5
6
with open('data.csv','w',encoding='utf-8-sig') as f:
    row=cursor.fetchone()
    while row is not None:
        s=','.join("%s"%i for i in row)
        f.writelines(s+'\n')
        row=cursor.fetchone()
 |