当我尝试使用用户mysql
连接到"root"
时,我的应用程序返回"Access denied for user *"ODBC"@"localhost" (using password:NO)"*
。我知道为什么会这样。
我使用Tkinter之类的GUI,我只测试了Connection的脚本,它的确如此。
代码连接
import MySQLdb
class Conexao():
def __init__(self, host,user,passwd,db):
self.host = host
self.user = user
self.passwd = passwd
self.db = db
def getconnection(self):
try:
self.conn = MySQLdb.connect(host=self.host,
user = self.user,
passwd = self.passwd,
db = self.db)
print "Connected"
return self.conn.cursor()
except MySQLdb.Error,e:
print " error "+ str(e[1])
return e
代码应用
from Tkinter import *
import sys
sys.path.insert(0,'C:\\Users\\felipe.cunha\\Documents\\project')
from conexao.conexao import Conexao
"""
b.execute("select * from setor")
>>> b.fetchall()
"""
class View(Frame):
def __init__(self,master = None):
Frame.__init__(self)
self.master.title("teste")
self.create_menu()
def create_menu(self):#,width = self.width,height = self.height):
host = "localhost"
label_menu = Label(self.master,text = 'Login')
label_menu.pack()
entrada_menu_login = Entry(self.master)# user
entrada_menu_senha = Entry(self.master, show = "*")# passwd
conn = Conexao(host,entrada_menu_login.get(),entrada_menu_senha.get(),"dsti")
#conn = Conexao(host,"root","d04m10","dsti")
btn_login = Button(self.master,text="Logar",command = conn.getConnection)#self.show_entry_fields)
entrada_menu_login.pack()
entrada_menu_senha.pack()
btn_login.pack()
def show_entry_fields(self):
print(self.entrada_menu_login.get(), self.entrada_menu_senha.get())
app = View()
app.mainloop()
答案 0 :(得分:0)
问题是,在用户能够输入用户名或密码之前,在GUI启动时创建连接。在您创建连接时,entrada_menu_login
和entrada_menu_senha
都为空。
解决方案是在用户点击按钮之后才创建连接。
答案 1 :(得分:0)
代码看起来像 -
class View(Frame):
def __init__(self,master = None):
Frame.__init__(self)
self.master.title("teste")
self.create_menu()
def create_menu(self):#,width = self.width,height = self.height):
host = "localhost"
label_menu = Label(self.master,text = 'Login')
label_menu.pack()
self.entrada_menu_login = Entry(self.master)# user
self.entrada_menu_senha = Entry(self.master, show = "*")# passwd
btn_login = Button(self.master,text="Logar",command = self.buttonListener) #self.show_entry_fields
entrada_menu_login.pack()
entrada_menu_senha.pack()
btn_login.pack()
def buttonListener(self):
conn = Conexao(host,self.entrada_menu_login.get(),self.entrada_menu_senha.get(),"dsti")
#conn = Conexao(host,"root","d04m10","dsti")
dbcursor = conn.getConnection()
#Do the rest of the logic you want to do.