【问题标题】:Python extract mysql to csvPython将mysql提取到csv
【发布时间】:2018-11-21 10:34:08
【问题描述】:

我试图将数据从 mysql 提取到 csv 文件。问题是行的顺序与mysql中的顺序不同。

在 mysql 中,我在 uid 表 1,2,3,4,5,6,7,8,9,10,11 中有这个,但响应是 10,9,11,2,1,4,3, 6,5,8,7。

cursor=conn.cursor()
cursor.execute("SELECT * FROM test ORDER BY uid;")
rows = cursor.fetchall()

#rows = sorted(rows1)
allResults = {}
for row in rows:
#for row in rows:
    uid = str(row[0])
    data = str(row[1])

    allResults[uid] = [uid,data]

    #numbers.append(allResults)


return allResults


def getCSV():

    if request.method == 'POST':
        nr = str(request.form['nrsearch']).strip()
        try = str(request.form['trysearch']).strip()
        year = str(request.form['yearsearch']).strip()

        allResults = readFromDBCSV(nr, try, year)
        #print(allResults)

        filename = str(nr)+"."+str(try)+"."+str(year)+'.csv'

        if len(allResults) > 0:
            with open('static/CSV/'+str(filename), 'wb') as csvfile:
                CSVwriter = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)
                CSVwriter.writerow(['test'])
                for result in allResults:
                    CSVwriter.writerow(allResults[result])
            return '''DONE '''+str(len(allResults))+''' RESULTS<br>
    <form method=post enctype=multipart/form-data action="/doneCSV/">
    <input type="hidden" name="filename" value="'''+str(filename)+'''">
    <input type=submit name="Download CSV" value="Download CSV"><br>
    <a href="/getCSV/">Return</a>'''
    else:   
    return 'NO RESULTS<br><a href="/getCSV/">Return</a>'

    return render_template('searchCSV.html')

【问题讨论】:

  • 感谢您的好意。我已经尝试了你所有的技巧,但没有运气:(我是python中的新手:(:(我已经将代码更改为:cursor=conn.cursor() cursor.execute("SELECT * FROM test2 ORDER BY uid; ") for row in cursor: uid = str(row[0]) data = str(row[1]) allResults[uid]= [uid,data] print(allResults[uid]) return allResults 为什么是 print(allResults [uid]) 给出正确的顺序?(1,2,3...)。

标签: python mysql sql csv


【解决方案1】:

在您的情况下:您正在存储到字典变量中。通常字典不会保留您插入的顺序。 如果您要下单,请使用OrderedDict()

from collections import OrderedDict
allResults   = OrderedDict()

我的其他建议是: 使用 pandas 函数,您可以轻松保存到 CSV 中

检查 read_sql 函数 http://pandas.pydata.org/pandas-docs/version/0.22/io.html#sql-queries

【讨论】:

  • 你能回答OP的问题吗?问题是“问题是行的顺序与 mysql 中的顺序不同。”
  • 请检查我现在给出的答案@brunodesthuilliers
【解决方案2】:

Python dicts 是无序的 - 这是 FWIW 的文档。如果您想保持广告顺序,请使用 collection.OrderedDict 而不是 dict

现在对于您的用例,解决方案要简单得多:根本不使用 dict,或者使用 cursor.fetchall() 返回的列表,或者更好的是,只需将光标传递给编写器(光标是可迭代)。

cursor.execute(your_query_here)
with open(path/to/file.csv, "wb") as f:
    writer = csv.writer(f, ....)
    writer.writerows(cursor)

【讨论】:

  • :)) 谢谢它的工作:) 。我在 3 天内尝试过,但没有运气。再次感谢
  • 很高兴我能提供帮助 - 如果它解决了您的问题,请随时接受答案;)
猜你喜欢
  • 2021-05-17
  • 1970-01-01
  • 2016-04-19
  • 2021-01-16
  • 2019-02-22
  • 1970-01-01
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多