令人困惑的python mysql连接问题

时间:2013-10-12 16:38:41

标签: python mysql mysql-connector

大家好,我目前正在学校的一个python项目中工作。首先,我想说清楚我不是一个python程序员(我只是被召唤来解决这个项目中的火焰,因为没有其他人愿意,而且我很勇敢地说是)。

我这里有以下问题。我必须编写一个连接到现有localhost MySQL数据库的方法(我使用的是连接器版本1.0.12和python 2.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开发人员来说非常容易,所以任何帮助都会受到高度赞赏。

提前致谢。

1 个答案:

答案 0 :(得分:0)

两个版本之间的区别并不在于您在第二个版本中对参数进行了硬编码,而是您通过关键字args而不是位置参数调用。 MySQL连接器的文档似乎没有给出实际的位置顺序,并且没有理由认为它们按照你给出的顺序排列,所以看起来你应该总是调用kwarg:

cnxOMC = mysql.connector.connect(user=user, password=password,host=host,database=database)
相关问题