由于错误而无法创建数据库MySQLConnection'对象不可调用

时间:2018-02-21 06:10:16

标签: python sql database

我使用mysql.connector连接到我的数据库,但是当我尝试使用以下类声明并使用connect函数(创建数据库并使用它)时,我收到错误

  

TypeError:'MySQLConnection'对象不可调用

连接数据库时我做错了吗?

class database_creator():

    def __init__(self , username , password):
        self.username = username
        self.password = password 
        self.cursor = None  # this is the cursor 
        self.connect = None  # this is the cnx the mysql object 
        self.tables = []   # this shows how many databse table are there

    def initializer(self): # sets the cursor and starts the engine 

        self.connect = mysql.connector.connect(user=self.username, password= self.password)
        self.cursor = self.connect.cursor()

    def connect (self , c_database ):
        # c_database is the name of the database that i want to make

            self.cursor.execute("CREATE DATABASE(c_database)")


            self.connect.database = c_database #

1 个答案:

答案 0 :(得分:0)

有关详情,请阅读Connector/Python Connection Arguments

通常我会直接使用sql创建数据库,并且只使用mysql-connector-python运行sql插入或查询。

但是,在您的情况下,错误可能是由于您尝试执行数据库创建sql时的错误,您应该将其更改为:

def connect (self , c_database ):
    # c_database is the name of the database that i want to make

        self.cursor.execute("CREATE DATABASE {}".format(c_database))


        self.connect.database = c_database #

但一般情况下,您应该尝试检查c_database是否要创建存在。如果是,您只需指定c_database字符串;如果没有,那么只有你将创建名为c_database

的数据库
def createmysqldb(host, port, c_database, user, password):
    cnx = mysql.connector.connect(host=host, port=port, user=user, password=password)
    cursor = cnx.cursor()
    try:
        cnx.database = c_database
    except mysql.connector.Error as err:  # maybe db does not exist
        if err.errno == mysql.connector.errorcode.ER_BAD_DB_ERROR:
            try:
                cursor.execute(
                    "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(c_database))
            except mysql.connector.Error as err:
                print("Failed creating database: {}".format(err))
                return
            cnx.database = c_database
        else:
            print(err)
            return