Python Forum

Full Version: how to save the data from MySQL to CSV in Flask
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi..I want to save the data from MySQL to CSV in Flask. The data that need to be saved, consists of id,q1 and q2. The problem is, it does not generate all the data. Instead, it just shown id,q1 and q2 only in the csv, as shown example below:

-------------------
id q1 q2
------------------
id q1 q2
-------------------


The code are below:
@app.route('/article/<string:id>/')
def article(id):
# Create cursor
    cur = mysql.connection.cursor()

    # Get article
    result = cur.execute("SELECT id,q1,q2 FROM table WHERE id = %s", [id])

    article = cur.fetchall()

    with open('database.csv', 'w', newline= '') as f:
            a = csv.writer(f, delimiter=',')
            a.writerows(article)  ## closing paren added

    if result > 0:
        return render_template('article.html', article=article)
    else:
        msg = 'No Articles Found'
        return render_template('article.html', msg=msg)
Hope you can help me
In reality, you don't even need csv.writer as the structure is so simple, but if used:
remove line 9, instead use something like (untested):
with open('database.csv', 'w', newline= '') as f:
    cwrtr = csv.writer(f, delimiter=',')
    while article = cur.fetchone():
        cwrtr.write(f"article[0], article[1], article[2]\n")
I have tried your code, but got error:
Error:
File "c:/Users/User/Documents/first/app.py", line 78 while article = cur.fetchone(): ^ SyntaxError: invalid syntax
What's the problem actually?Sorry for asking
I did say it was untested.
I guess it has to be done a bit differently:
with open('database.csv', 'w', newline= '') as f:
    cwrtr = csv.writer(f, delimiter=',')
    while True:
        article = cur.fetchone()
        if len(article == 0):
            break
        cwrtr.write(f"article[0], article[1], article[2]\n")
thanks