1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Can't connect to mysql database from the python code using mysql.connector

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I m unable to connect to my database and it gives this error that object is not callable. I did search up the error and even what it means. I changed a lots of stuff in the code but it didn't work for me. like instead of using the import mysql.connector.connect() to connect to the database I used connection.MySQLConnection() and it still gave the same error. I even changed the variable names because I saw some where that variables could also be an issue some time. It didn't help either, the problem might not be big but I m just having a hard time to fix it.

    def Database_connection(self):

    dbhost = "localhost"
    dbuser = "test"
    dbpass = "1234"
    database_name ="school"

    #CONNECTION OF DB
    self.mdb = mysql.connector.connect(

    host = dbhost,
    password = dbpass,
    user = dbuser,

    )
    #Cursor to mysql database
    cursor = self.mdb.cursor()

    #Creates database if it doesn't exists
    cursor.execute(f'CREATE DATABASE IF NOT EXISTS {database_name}')

    self.mdb = mysql.connector.connect(

    host = dbhost,
    password = dbpass,
    user = dbuser,
    db = database_name,
    )
    return self.mdb


    def insert_new_student(self):

    try:
    conn = self.Database_connection()

    if conn is None:
    return

    cursor = conn().cursor()

    conn.commit()
    cursor.close()
    conn.close()

    except mysql.connector.Error as err: #Handles Error

    print(f"Error: {err}")



    The Error this code generates is:

    line 380, in insert_new_student
    cursor = conn().cursor()
    ^^^^^^
    TypeError: 'MySQLConnection' object is not callable

    Continue reading...

Compartilhe esta Página