【问题标题】:How to import mysql data to .txt file using python 3.5?如何使用 python 3.5 将 mysql 数据导入 .txt 文件?
【发布时间】:2017-04-26 10:44:37
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • writelines() 假设有一个行数组,你必须使用write(row + "\n")
  • stackoverflow.com/questions/12377473/… 使用 write 而不是 writelines。
  • 我刚刚使用这段代码得到了表结构:for row in result: newfile.write("\t".join(row)) 但没有来自 sql 的数据。

标签: python mysql python-3.x


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2013-08-05
    • 2014-04-24
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多