gpt4 book ai didi

python - 如何使用 python 3.5 将 mysql 数据导入到 .txt 文件?

转载 作者:行者123 更新时间:2023-11-30 22:00:13 25 4
gpt4 key购买 nike

我正在尝试使用 python 3.x 将 mysql 数据导入 .txt 文件,但看起来我遗漏了一些东西。期望是,数据应该以表格/列格式导入到文件中。我尽了最大努力来获得解决方案,但我没有得到我需要的东西。

下面是我的代码:

import pymysql.cursors
import pymysql
import sys
import os

# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password="",
db='jmeterdb',
cursorclass=pymysql.cursors.DictCursor)

try:
with connection.cursor() as cursor:
# Select all records
sql = "select * from emp"
cursor.execute(sql)

# connection is not autocommit by default. So you must commit to save
# your changes.
result = cursor.fetchall()
newfile = open("db-data.txt","a+")
for row in result:
newfile.writelines(row)

print(result)
newfile.close()

finally:
connection.close()

在执行 print(result) 时,python 在终端上向我显示数据,但在 db-data.txt 文件中,它仅显示列名。

预期结果:

Column_Name1 Column_Name2 Column_Name3
data1 data2 data3
data1 data2 data3

最佳答案

此代码为上述问题生成的预期输出如下:

import pymysql.cursors
import pymysql
import sys
import os

# Open database connection
connection = pymysql.connect(host='localhost',
user='root',
password="",
db='jmeterdb',
cursorclass=pymysql.cursors.DictCursor)
# prepare a cursor object using cursor() method
with connection.cursor() as cursor:
# Prepare SQL query to select a record into the database.
try:

sql = "SELECT * FROM EMP order by ename asc"
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
# print(results)
if results:
newfile = open("db-data.txt","a+")
newfile.write('ename'+"\t"+'jobs'+"\t"+"salary"+"\t"+'comm'+"\t"+'manager'+"\t"+'hiredate'+"\t"+'deptno'+"\t"+'empno'+"\n")

for index in results:
ltr=[]
ltr.append(index['ename'])
ltr.append(index['job'])
ltr.append(index['sal'])
ltr.append(index['comm'])
ltr.append(index['mgr'])
ltr.append(index['hiredate'])
ltr.append(index['deptno'])
ltr.append(index['empno'])
lenltr=len(ltr)
for i in range(lenltr):
newfile.write('{}'.format(ltr[i]))
newfile.write("\t")
print(ltr[i])
newfile.write("\n")


# # Now print fetched result
#print("ename=%s,empno=%d,job=%d,hiredate=%d,comm=%s,sal=%d,deptno=%d,mgr=%d" %(ename, empno, job, hiredate, comm, sal, deptno, mgr))
# print(index)
except:
print ("Error: unable to fecth data")
# disconnect from server
connection.close()
newfile.close()

关于python - 如何使用 python 3.5 将 mysql 数据导入到 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43631955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com