Ben
Ben

Reputation: 569

Why am I unable to connect to a mysql database using python and mysql.connector?

I am trying to connect to a mysql database, but having issues. I am trying to use mysql connector (not sure if this is the most efficient library to use), but I am having an error.

Here is my basic script:

import mysql.connector

def test_sql_query():
    db = mysql.connector.connect(host='hostname', database='db', user='dbuser', password='dbpass' port=000)
    cur = db.cursor()
    if db.is_connected():
        print('Connected to MySQL database')
    try:
        sql_command = "select * from test where test like '%FileUploadAgent%' and status='00' order by test desc;"
        cur.execute(sql_command)
        db.commit()
        rows = cur.fetchall()
        for row in rows:
            print "   ", row[1][1]
    except:
        print "did not work"
    db.close()

Error:

 File "sql_test.py", line 44, in <module>
    test_sql_query()
  File "sql_test.py", line 6, in sterling_agent_sql_query
    db = mysql.connector.connect("host='hostname.com' database='dbname' user='dbuser' password='dbpassword' port='000'")
  File "/Library/Python/2.7/site-packages/mysql/connector/__init__.py", line 179, in connect
    return MySQLConnection(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 57, in __init__
    super(MySQLConnection, self).__init__(*args, **kwargs)
TypeError: __init__() takes exactly 1 argument (2 given)

I am assuming that I am doing the connection wrong.

Upvotes: 1

Views: 5317

Answers (3)

Kassian
Kassian

Reputation: 11

I got the same problem my solution was to uninstall MySQL connector.

python -m pip uninstall mysql-connector

And then reinstall it using:

python -m pip install mysql-connector

and it works for me.

Upvotes: 0

Jeffrey Naujok
Jeffrey Naujok

Reputation: 1

You have the format of the connect incorrect, putting all of the variables inside of quotes makes the method treat it as a single, string input to the method.

db = mysql.connector.connect("host='hostname' database='db' user='dbuser' password='dbpass' port='000'")

should be

db = mysql.connector.connect(
    host='hostname',
    database='db',
    user='dbuser',
    password='dbpass',
    port=0)

Note that your port value also should be a valid port (not the echo port) for the database.

Upvotes: 0

Andy
Andy

Reputation: 50630

The parameter you are passing to .connect() is wrong. You are passing a string. Instead, each of those should be their own parameter.

db = mysql.connector.connect(host='hostname', 
    database='db', 
    user='dbuser', 
    password='dbpass', 
    port=000)

Additionally, port needs to be an integer, not a string. I also assume that the 000 you have is example data. If not, that's not valid.

Upvotes: 1

Related Questions