Import Mysql data to Excel

Asked

Viewed 340 times

3

To want to import data from Mysql to excel using Python, when I try to make it from an error of tuple. Someone with more experience can help me?

I followed the code and the error:

# coding=utf-8

from Tkinter import *
from os import popen
import tkMessageBox
import sys
import ttk
import os,tkFileDialog
from PIL import ImageTk,Image
import MySQLdb
import PIL
import xlwt
import xlrd
import xlutils

class criarXLS:
    def __init__(self,master=None):
        self.master = master
        self.tela = Frame(width=500,height=300)
        self.tela.place(x=10,y=10)
        self.botGerar = Button(self.tela,text='Gerar Rel.',command=self.criarTabela)
        self.botGerar.grid(row=1,column=1)

    def conexaoBanco(self):
        BANCO = "ipuser_cde"
        USER = "root"
        PASSWD = "charlote1"
        HOST = "192.168.1.249"
        try:
            con = MySQLdb.connect(db=BANCO, user=USER, passwd=PASSWD, host=HOST)
            print("Conseguiu conectar ao Banco de Dados")
            #self.desativarOPDB()
        except MySQLdb as erro:
            print("Nao conseguiu conectar ao Banco de Dados.: ", erro)

        return con

    def criarTabela(self):
        self.workbook = xlwt.Workbook()
        self.worksheet = self.workbook.add_sheet('Rel.User')

        db = self.conexaoBanco()
        cursor = db.cursor()
        sql = "select iduser,nome,email from usuario"
        cursor.execute(sql)
        dadosUser = cursor.fetchall()


        self.worksheet.write(0,0, u'ID')
        self.worksheet.write(0,1, u'Nome')
        self.worksheet.write(0,2, u'Email')
        for i,user in enumerate(dadosUser()):
            self.worksheet.write(i + 1, 0, user['iduser'])
            self.worksheet.write(i + 1, 1, user['nome'])
            self.worksheet.write(i + 1, 2, user['email'])
        self.workbook.save('Rel-User.xls')
        db.close()


root = Tk()
root.geometry('1350x700+0+0')
root.configure(background='Grey21')
criarXLS(root)
root.mainloop()

Error:

Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
    return self.func(*args)
  File "E:/CharIp ServerFTP_1.1/CharIP_1.1.5/criar_rel.py", line 62, in criarTabela
    for i,user in enumerate(dadosUser(0)):
TypeError: 'tuple' object is not callable

1 answer

3


dadosUser = cursor.fetchall()
# ...
for i,user in enumerate(dadosUser()):
    # ...

You’re trying to use dadosUser() as a function, dadosUser contains a list of tuples or an empty list according to documentation.

To iterate over the list, remove ():

for i,user in enumerate(dadosUser):
    # ...
  • made the change and gave me the following error:'Managed to connect to Database Exception in Tkinter callback Traceback (Most recent call last): File "C: Python27 lib-Tk Tkinter.py", line 1532, in call Return self.func(*args) File "E:/Charip Serverftp_1.1/Charip_1.1.5/cria_rel.py", line 52, in creatTable self.worksheet.write(i + 1, 0, user['iduser']) Typeerror: tuple indices must be integers, not str'

  • I did as I did

  • for i,user in enumerate(dataUser): self.worksheet.write(int(i) + 1, 0, user['iduser']) self.worksheet.write(int(i) + 1, 1, user['name']) self.worksheet.write(int(i) + 1, 2, user['email']) self.workbook.save('Rel-User.xls') db.close()

  • the following error:Exception in Tkinter callback Traceback (Most recent call last): File "C: Python27 lib-Tk Tkinter.py", line 1532, in call Return self.func(*args) File "E:/Charip Serverftp_1.1/Charip_1.1.5/cria_rel.py", line 52, in creatTable self.worksheet.write(int(i) + 1, 0, user['iduser']) Typeerror: tuple indices must be integers, not str

  • add to skype [email protected]

  • @Diuniorronaldobrumlauser Make that change: self.worksheet.write(i + 1, 0, user[0]), self.worksheet.write(i + 1, 1, user[1]), and self.worksheet.write(i + 1, 2, user[2]), this way you access user by index.

  • Dude vlw by help worked super well, I spent hours cracking my head, to solve this thank you even

  • @Diuniorronaldobrumlauser Arrange! if possible mark the answer as "accept" by clicking on the arrow below the score!

  • excuse the ignorance and that I am new in this where I mark the answer?

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.