Search code examples
mysqlsqlpython-3.xpymysql

How to add column title to Excel while exporting result table from SQL query with Python


I have been trying to export a result table from a SQL query, but only the records inside the table is displayed in the Excel table. I am using MySQL and python(3.9.11) to run this code. Here is the code that I have been using to do so.

import pymysql
dbconn = pymysql.connect(<db details>)
cus = dbconn.cursor()
cus.execute('sql query')
res = cus.fetchall()
data = []
for i in res:
    data += list(i)
var = open('main.csv','w')
for i in data:
    var.write(str(i))
var.close()

Also, the result table's all columns data is written in a single column. I tried and adding a var.write('/n'), but it will convert the rows into columns.


Solution

  • import pymysql
    import csv
    dbconn = pymysql.connect(DB Connection details)
    cus = dbconn.cursor()
    cus.execute("sql query here")
    res = cus.fetchall()
    column_names = [i[0] for i in cus.description]
    fp = open('main.csv', 'w')
    myFile = csv.writer(fp, lineterminator = '\n')
    myFile.writerow(column_names)   
    myFile.writerows(res)