mysql csv 字段名_使用python将mysql查询写入csv,需要显示字段名

本文展示了如何使用Python的pymysql和csv模块将MySQL查询结果写入CSV文件,并确保CSV文件的第一行是字段名。通过获取cursor.description来获取列名,然后将数据和列名合并写入CSV。
摘要由CSDN通过智能技术生成

我有以下资料:import MySQLdb as dbapi

import sys

import csv

dbServer='localhost'

dbPass='supersecretpassword'

dbSchema='dbTest'

dbUser='root'

dbQuery='SELECT * FROM pbTest.Orders;'

db=dbapi.connect(host=dbServer,user=dbUser,passwd=dbPass)

cur=db.cursor()

cur.execute(dbQuery)

result=cur.fetchall()

c = csv.writer(open("temp.csv","wb"))

c.writerow(result)

这会造成混乱。我熟悉使用打印记录[0]等。不确定如何设置格式。生成类似于查询在控制台中的内容。我无法从mysql服务器执行简单的INTO OUTFILE。

更新

已经8年了;我仍然偶尔得到关于这个问题的更新或询问。

正如在一些注释中所述,DBAPI中的cursor.description正是我所寻找的。

Python 3中有一个更现代的例子,它使用pymysql驱动程序连接到MariaDB,后者将选择所有行并将其提取到元组中,将行标题/描述提取到列表中。然后我将这两个数据结构合并成一个列表,即written to a csv file。

头名称是结果列表中的第一个条目;以线性方式将结果写入文件可确保行头是CSV文件中的第一行。import pymysql

import csv

import sys

db_opts = {

'user': 'A',

'password': 'C',

'host': 'C',

'database': 'D'

}

db = pymysql.connect(**db_opts)

cur = db.cursor()

sql = 'SELECT * from schema_name.table_name where id=123'

csv_file_path = '/tmp/my_csv_file.csv'

try:

cur.execute(sql)

rows = cur.fetchall()

finally:

db.close()

# Continue only if there are rows returned.

if rows:

# New empty list called 'result'. This will be written to a file.

result = list()

# The row name is the first entry for each entity in the description tuple.

column_names = list()

for i in cur.description:

column_names.append(i[0])

result.append(column_names)

for row in rows:

result.append(row)

# Write result to file.

with open(csv_file_path, 'w', newline='') as csvfile:

csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

for row in result:

csvwriter.writerow(row)

else:

sys.exit("No rows found for query: {}".format(sql))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值