Python Forum
how to save the data from MySQL to CSV in Flask - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html)
+--- Thread: how to save the data from MySQL to CSV in Flask (/thread-23444.html)



how to save the data from MySQL to CSV in Flask - farah97 - Dec-30-2019

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


RE: how to save the data from MySQL to CSV in Flask - Larz60+ - Dec-30-2019

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



RE: how to save the data from MySQL to CSV in Flask - farah97 - Dec-30-2019

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


RE: how to save the data from MySQL to CSV in Flask - Larz60+ - Dec-31-2019

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



RE: how to save the data from MySQL to CSV in Flask - farah97 - Jan-03-2020

thanks