我要在mysql表中导出csv文件
我的代码是:
import csv
import MySQLdb
def importcsv():
mydb = MySQLdb.connect(host='localhost', user='me', passwd='1234', db='Data1', use_unicode=0, charset='utf8')
cursor = mydb.cursor()
csv_data = csv.reader(open('input.csv', newline='', encoding='utf8'))
for row in csv_data:
cursor.execute('INSERT INTO sensor(Date, Time, Data)' 'VALUES("%s", "%s", "%s")', row)
mydb.commit()
cursor.close()
print ("CSV has been imported into the database")
def exportcsv():
mydb = MySQLdb.connect(host='localhost', user='me', passwd='1234', db='Data1', use_unicode=0, charset='utf8')
cursor = mydb.cursor()
cursor.execute("SELECT * FROM sensor")
with open('out.csv', 'w', newline='', encoding='utf-8') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=';')
csv_writer.writerow([ i[0] for i in cursor.description ])
csv_writer.writerows(cursor.fetchall())
mydb.commit()
cursor.close()
print ("CSV has been exported into the database")
可以,但是out.csv的数据是
如何导出类似的csv文件
input.csv的内容是
日期时间数据(标题)
2017/01/01 12:00 1
2017/01/02 13:00 2
答案 0 :(得分:2)
实际上,您试图从MySQL提取的数据是字节字符串格式,您必须将其解码为字符串格式才能摆脱b,您可以尝试这样的操作。
b"your bytecode string".decode()