python - 使用csv从mysql数据库导出数据

标签 python mysql shell csv

我需要一个 python 脚本来从我的数据库 XXXX 生成 csv 文件。我写了这个脚本,但我有问题:

import mysql.connector
import csv
filename=open('test.csv','wb')
c=csv.writer(filename)

cnx = mysql.connector.connect(user='XXXXXXX', password='XXXXX',
                              host='localhost',
                              database='XXXXX')


cursor = cnx.cursor()

query = ("SELECT `Id_Vendeur`, `Nom`, `Prenom`, `email`, `Num_magasin`, `Nom_de_magasin`, `Identifiant_Filiale`, `Groupe_DV`, `drt_Cartes`.`gain` as 'gain',  `Date_Distribution`, `Status_Grattage`, `Date_Grattage` FROM `drt_Cartes_Distribuer`,`drt_Agent`,`drt_Magasin`,`drt_Cartes` where `drt_Cartes_Distribuer`.`Id_Vendeur` = `drt_Agent`.`id_agent` AND `Num_magasin` = `drt_Magasin`.`Numero_de_magasin` AND `drt_Cartes_Distribuer`.`Id_Carte` = `drt_Cartes`.`num_carte`")

cursor.execute(query)

for Id_Vendeur, Nom, Prenom, email, Num_magasin, Nom_de_magasin, Identifiant_Filiale, Groupe_DV, gain, Date_Distribution, Status_Grattage, Date_Grattage in cursor:
    c.writerow([Id_Vendeur, Nom, Prenom, email, Num_magasin, Nom_de_magasin, Identifiant_Filiale, Groupe_DV, gain, Date_Distribution, Status_Grattage, Date_Grattage] )

cursor.close()
filename.close()
cnx.close()

当我在 phpmyadmin 上执行命令时,它看起来工作得很好,但是从我的 shell 中我收到了这条消息:

# python test.py
Traceback (most recent call last):
  File "test.py", line 18, in <module>
    c.writerow([Id_Vendeur, Nom, Prenom, email, Num_magasin, Nom_de_magasin, Identifiant_Filiale, Groupe_DV, gain, Date_Distribution, Status_Grattage, Date_Grattage] )
UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 5: ordinal not in range(128)

最佳答案

看起来您正在使用 Python 2.7 的 csv。 Quoting docs :

Note This version of the csv module doesn’t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe; see the examples in section Examples.

选项,选择其中之一:

  1. 点击文档链接,转到示例部分,然后相应地修改您的代码。
  2. 使用带有 unicode 支持的 csv 数据包,例如 https://pypi.python.org/pypi/unicodecsv

关于python - 使用csv从mysql数据库导出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34085259/

相关文章:

linux - 需要使用 bash shell 脚本批量重命名文件的帮助

python - 如何向当前词袋分类添加另一个特征(文本长度)? Scikit学习

python - 使用 python 的 strptime 解析带有任何分隔符的日期

python - 如何在 matplotlib 中单独显示数字?

python - 如何在GoCV中提取信心

mysql - 更改排序规则后替换多个表中的多个外来字符

linux - 在 bash 中获取重定向位置

php - PDO:将 MySQL 函数传递给 bindValue/bindParam

mysql - 卡在具有多个 JOIN 的 MySQL 查询上

bash - 在 bash 脚本中使用 if 语句检查包是否已安装时遇到问题