如何将lineedit中的东西插入MySQL?

时间:2015-03-09 18:31:10

标签: python mysql pyqt

我正在制作一个允许我向数据库添加问题的表单。我编写了代码,但是当我尝试它时,我收到此错误(' AttributeError:'模块'对象没有属性' GetTable')

错误在于我的代码't = self.dbu.GetTable()'

的这一部分
@QtCore.pyqtSignature("on_add_btn_clicked()")
def Add_btn(self):
    Question = self.Question_lineEdit.text()#Grabs the text from all line edit fields
    Answer = self.Answer_lineEdit.text()
    IsmultiChoice = self.IsMultiChoice_lineEdit.text()
    if not Question:
        QtGui.QMessageBox.warning(self, 'Warning', 'Username Missing')
    else:
        t = self.dbu.GetTable()
        print (t)
        for col in t:
            if Question == col[1]:
                QtGui.QMessageBox.warning(self, 'Warning', 'Question Taken. :(')#Checks the database and warns if the database does exist                               
        else:
            self.dbu.AddEntryToTable (Question, Answer, isMultiChoice)
            QtGui.QMessageBox.information(self, 'Success', 'User Added Successfully!')#If everythings is okay it adds the user 
            self.close()

这是我的数据库代码:

import mysql.connector
from mysql.connector import errorcode
from datetime import datetime



class DatabaseUtility: 
    def __init__(self, database, Tablename,):
        self.db = database
        self.Tablename = Tablename




        self.cnx = mysql.connector.connect(user = 'root',
                                    password = '',
                                    host = 'localhost')


        self.cursor = self.cnx.cursor()

    def ConnectToDatabase(self):
        try:
            self.cnx.database = self.db 
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_BAD_DB_ERROR:
                self.CreateDatabase()
                self.cnx.database = self.db
            else:
                print(err.msg)

    def CreateDatabase(self):
        try:
            self.RunCommand("CREATE DATABASE %s DEFAULT CHARACTER SET 'utf8';" %self.db)
        except mysql.connector.Error as err:
            print("Failed creating database: {}".format(err))



    def GetTable(self):
        self.Tablename()
        return self.RunCommand("SELECT * FROM %s;" % self.Tablename)











    def GetColumns(self):
        return self.RunCommand("SHOW COLUMNS FROM %s;" % self.Tablename)




    def RunCommand(self, cmd):
        print ("RUNNING COMMAND: " + cmd)
        try:
            self.cursor.execute(cmd)
        except mysql.connector.Error as err:
            print ('ERROR MESSAGE: ' + str(err.msg))
            print ('WITH ' + cmd)
        try:
            msg = self.cursor.fetchall()
        except:
            msg = self.cursor.fetchone()
        return msg

    def AddEntryToTable(self, Question, Answer,IsMultiChoice):
        cmd = " INSERT INTO " + self.Tablename + " (Question, Answer, IsMultiChoice)"
        cmd += " VALUES ('%s', '%s', '%s');" % (Question, Answer, IsMultiChoice)
        self.RunCommand(cmd)


    def __del__(self):#Deconstructer class
        self.cnx.commit()
        self.cursor.close()
        self.cnx.close()

















if __name__ == '__main__':
    db = 'UsernamePassword_DB'
    Tablename = 'questiontable'



    dbu = DatabaseUtility(db, Tablename)

我做错了什么,如何纠正?

1 个答案:

答案 0 :(得分:1)

我需要看一些额外的代码才能确定(请参阅我的评论)。但是现在我的猜测是它与你如何首次实例化或引用dbu变量/属性有关。如果您所做的只是从另一个文件导入,那么因为dbu在该文件的main()(在您提供的代码段中)中创建,可能就是问题所在。例如, 不正确

from whatever import dbu  # wrong
from whatever.main import dbu  # Also wrong. In fact I don't think this would even work

相反,将DatabaseUtility直接导入到脚本中,然后实例化dbu,如:

from whatever import Database Utility
class SomeClass(object):
...
def startDB(self, db, Tablename):
  self.dbu = DatabaseUtility(db, Tablename)

我猜这是因为错误信息显示模块没有属性,而不是提及实际的类。这是我期望看到的错误示例:

In [31]: class MyClass(object):
    one = 1
   ....:     
In [32]: myc = MyClass()
In [33]: myc.one
Out[33]: 1
In [34]: myc.two
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-34-4bae87671838> in <module>()
----> 1 myc.two

AttributeError: 'MyClass' object has no attribute 'two'

注意它是怎么说 MyClass 是问题,而不是“模块”。

可能无关,您可能希望从self.Tablename()中删除DatabaseUtility.GetTable()。您定义类的方式,TableDatabaseUtility类的属性,但是通过包含您尝试调用它的括号,就好像它是< em>方法(如GetTable是)。