0

I'm upgrading a database application from Python 2.7 to 3.4. I originally used mysqldb, but I'm trying to switch to mysql-connector. My database connection fails with an internal TypeError. Here's the code and the error:

import mysql.connector

try:
  dbh = mysql.connector.connect("localhost","pyuser","pypwd","jukebox")
except mysql.connector.Error as err:
  print("Failed opening database: {}".format(err))
  exit(1)

and here's the error:

# python loadcd.py
Traceback (most recent call last):
  File "loadcd.py", line 12, in <module>
    dbh = mysql.connector.connect("127.0.0.1","pyuser","pypwd","jukebox")
  File "/usr/local/lib/python3.4/dist-packages/mysql/connector/__init__.py", line 179, in connect
    return MySQLConnection(*args, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/mysql/connector/connection.py", line 57, in __init__
    super(MySQLConnection, self).__init__(*args, **kwargs)
TypeError: __init__() takes 1 positional argument but 5 were given

I'm at a loss. The exact same connection works with mysqldb, and I can connect with the same credentials using PHP or at the command line.

pbft
  • 41
  • 5

2 Answers2

1

You should provide keyword arguments:

dbh = mysql.connector.connect(host="localhost",user="pyuser",password="pypwd",database="jukebox")
GProst
  • 9,229
  • 3
  • 25
  • 47
  • Big improvement - I missed the need for named parameters. However, I'm now getting '111 Connection Refused' errors. Same exact hostname, username, and password as I had working before with mysqldb. – pbft Oct 08 '20 at 19:48
  • Does this answer help you? https://stackoverflow.com/a/1420862/6250385 – GProst Oct 08 '20 at 19:54
  • Yes - that did it. My bind-address was the ip address of the server (192.168.1.10 in this case). Interesting that 'localhost' worked in python with mysqldb, but mysql.connector needed 192.168.1.10. – pbft Oct 08 '20 at 22:31
1

Use this and replace the values as per your configuration:

import mysql.connector

mydb = mysql.connector.connect(host="localhost",
                               user="yourusername",
                               password="yourpassword")

print(mydb)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Aniket Singh
  • 11
  • 1
  • 3