Article Directory
1 Basic structure
1.1 Data
1.2 Data structure
2 codes
- code:
import mysql.connector
import csv
def getPerson():
# 数据库初始化
cnx = mysql.connector.connect(user='root', password='root', database='test')
cursor = cnx.cursor()
query = 'SELECT * FROM person'
cursor.execute(query)
data = cursor.fetchall()
# 写入csv
with open('person.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['id', 'name', 'age', 'sex'])
for row in data:
lst = list(row)
i = 0
for index in lst:
# 字节转换
if isinstance(index,bytearray):
new = index.decode('utf-8')
lst[i] = new
i += 1
tup = tuple(lst)
writer.writerow(tup)
# 关闭连接
cursor.close()
cnx.close()
if __name__ == '__main__':
getPerson()
- output:
3 tip
Go converts data table to csv: https://blog.csdn.net/qq_45859826/article/details/131451336