令人困惑的python mysql连接问题

令人困惑的python mysql连接问题,python,mysql,mysql-connector,Python,Mysql,Mysql Connector,大家好,我目前在学校的一个python项目中工作。首先,我想明确我不是一个python程序员,我只是被要求在这个项目中灭火,因为没有其他人会这么做,我也勇敢地说是的 我这里有以下问题。我必须编写一个连接到现有localhost MySQL数据库的方法,我正在使用连接器版本1.0.12和Python2.6,然后做一些非常基本的工作。参数由GTK编写的GUI发送,我没有编写该接口。所以我写了我的方法如下: def compMySQL(self, user, database, password, d

大家好,我目前在学校的一个python项目中工作。首先,我想明确我不是一个python程序员,我只是被要求在这个项目中灭火,因为没有其他人会这么做,我也勇敢地说是的

我这里有以下问题。我必须编写一个连接到现有localhost MySQL数据库的方法,我正在使用连接器版本1.0.12和Python2.6,然后做一些非常基本的工作。参数由GTK编写的GUI发送,我没有编写该接口。所以我写了我的方法如下:

def compMySQL(self, user, database, password, db_level, table_level, column_level):
    sql_page_textview = self.mainTree.get_widget('sql_text_view')
    sql_page_textview.modify_font(pango.FontDescription("courier 10"))
    sql_page_buffer = sql_page_textview.get_buffer()

    #Gonna try connecting to DB
    try:
        print("Calling conn with U:{0} P:{1} DB:{2}".format(user,password,database))
        cnxOMC = mysql.connector.connect(user, password,'localhost',database)
    except:
        print "Error: Database connection failed. User name or Database name may be wrong"
        return

    #More code ...
但当我运行我的代码时,我得到以下信息:

Calling conn with U:root P:PK17LP12r DB:TESTERS
Error: Database connection failed. User name or Database name may be wrong 
我不知道为什么,因为发送的参数与打印出来的参数相同,告诉我其他人编写的GUI工作正常,它们是有效的登录参数。如果我使用GUI直接硬编码登录参数,一切正常,功能正常执行;以下代码执行得很好且平滑:

def compMySQL(self, user, database, password, db_level, table_level, column_level):
    sql_page_textview = self.mainTree.get_widget('sql_text_view')
    sql_page_textview.modify_font(pango.FontDescription("courier 10"))
    sql_page_buffer = sql_page_textview.get_buffer()

    #Gonna try hardcoding
    try:
        #print("Calling conn with U:{0} P:{1} DB:{2}".format(user,password,database))
        cnxOMC = mysql.connector.connect(user="root", password='PK17LP12r', host='localhost', database='TESTERS')
        print 'No prob with conn'
    except:
        print "Error: Database connection failed. User name or Database name may be wrong"
        return

    #more code ... 
控制台输出:

No prob with conn 
有什么想法吗,伙计们?这件真让我难受。我只是在学习Python,但我认为对于一个经验丰富的Python开发人员来说,这个问题非常简单,因此我们非常感谢您的帮助


提前谢谢

这两个版本之间的区别不是您在第二个版本中硬编码参数,而是您通过关键字args而不是位置args进行调用。docs for MySQL connector似乎没有给出实际的位置顺序,也没有理由认为它们符合您给定的顺序,因此看起来您应该始终通过kwarg调用:

cnxOMC = mysql.connector.connect(user=user, password=password,host=host,database=database)

请先修复缩进。在第一个代码块中,函数参数的顺序为用户、数据库、密码。但是,使用顺序似乎是用户、密码、数据库。您确定在调用函数时正在执行“root”、“TESTERS”、“PK17LP12r”等操作吗?此外,如果确实是这样,建议以后不要在公共网站上发布您的实际密码。