Search code examples
pythonmysql-pythonmysql-connectormysql-connector-pythondatabase-connection

TypeError: MySQLConnectionAbstract.__init__() takes 1 positional argument but 2 were given


I got the error below:

TypeError: MySQLConnectionAbstract.__init__() takes 1 positional argument but 
2 were given

Here is my db.py:

import mysql.connector

localhost = "localhost"
username = "Admin"
password = "test123"
db = "testing"
Connect = "host = '{}', user = '{}', password = '{}', db = '{}'".format(localhost, username, password, db)

cnn = mysql.connector.connect(Connect)  # line 16 error
# cnn = mysql.connector.connect(host ="localhost", user = "Admin", password = "test123", db = "testing")

If I write proper connect like below, then it worked.

cnn = mysql.connector.connect(host ="localhost", user = "Admin", password = "test123", db = "testing"

However, it won't work if I write the code like below:

cnn = mysql.connector.connect(Connect)

This is the completed error printed to the terminal:

Traceback (most recent call last):
  File "c:\Users\herok\Documents\MyApp 3\db.py", line 16, in <module>
    cnn = mysql.connector.connect(Connect)
  File "C:\Users\herok\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\__init__.py", line 273, in connect  
    return MySQLConnection(*args, **kwargs)
  File "C:\Users\herok\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection.py", line 72, in __init__
    super(MySQLConnection, self).__init__(*args, **kwargs)
TypeError: MySQLConnectionAbstract.__init__() takes 1 positional argument but 2 were given

Solution

  • When using this approach

    cnn = mysql.connector.connect(Connect)
    

    You are passing a string to connect function but the function doesn't accept string, it should receive keyword arguments as you did in the second approach

    cnn = mysql.connector.connect(host ="localhost", user = "Admin", password = "test123", db = "testing"
    

    so if you need to keep the connection string parameter in a variable so you can pass it to the connect function

    You can save the data as a dictionary add expand the dictionary when calling the function as the below

    connection_string_params = {
    "host":"localhost",
    "user":"Admin",
    "password":"test123",
    "db":"testing"
    }
    
    cnn = mysql.connector.connect(**connection_string_params)