0

I try to export the result of a query from mysql to a excel sheet. I use Msqlconnector, pandas librarys and i did that.

import mysql.connector
import pandas as pd

db = mysql.connector.connect(
  host="SQLServer",
  user="sqlusr",
  password="usrpasswd",
  database="sqldb"
)

cur = db.cursor()
cur.execute("SELECT * FROM direction_prix_proxi.matrice_sigma" \
                " LEFT JOIN direction_pri.trans_int_prix_gen using(SIGMA, UV)" \
                " LEFT JOIN direction_pri.trans_int_prix_module using(SIGMA, UV)" \
                " LEFT JOIN direction_pri.trans_int_vol1an_hors_module using(SIGMA, UV)" \
                " LEFT JOIN direction_pri.trans_int_vol1an_module using(SIGMA, UV);")

df = pd.DataFrame(cur.fetchall())
df.to_excel(file_path1, index = False, header=True)

It works but the columns names are not in the excel sheet, i have numbers instead.

I found that there is a function For get the columns names but i didnt succeed to implement it in the result.

print(cur.column_names)

Other solution i found :

result = cur.fetchall()
    num_fields = len(cur.description)
    field_names = [i[0] for i in cur.description]
    print(field_names)

    for value in result:
        print(value)

It displays the result in console, i want storage it in a data frame for export it on excel. How can i do that?

thanks

1
  • 1
    try using a cursor that returns dicts - i.e. cur = db.cursor(dictionary=True) - MySQLCursorDict Commented Dec 29, 2021 at 16:20

1 Answer 1

1

I'm not sure about using a cursor, but I use the following format when doing this and it works.

import mysql.connector
import pandas as pd

db_conn = mysql.connector.connect(
  host="SQLServer",
  user="sqlusr",
  password="usrpasswd",
  database="sqldb"
)

query = """SELECT * FROM direction_prix_proxi.matrice_sigma
            LEFT JOIN direction_pri.trans_int_prix_gen using(SIGMA, UV)
            LEFT JOIN direction_pri.trans_int_prix_module using(SIGMA, UV)
            LEFT JOIN direction_pri.trans_int_vol1an_hors_module using(SIGMA, UV)
            LEFT JOIN direction_pri.trans_int_vol1an_module using(SIGMA, UV);
        """

df = pd.read_sql(query, db_conn)
df.to_excel(file_path1, index = False, header=True)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.