Ben Ben - 2 years ago 80
SQL Question

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')
sql_command = "select * from test where test like '%FileUploadAgent%' and status='00' order by test desc;"
rows = cur.fetchall()
for row in rows:
print " ", row[1][1]
print "did not work"


File "", line 44, in <module>
File "", line 6, in sterling_agent_sql_query
db = mysql.connector.connect("host='' database='dbname' user='dbuser' password='dbpassword' port='000'")
File "/Library/Python/2.7/site-packages/mysql/connector/", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/Library/Python/2.7/site-packages/mysql/connector/", 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.

Answer Source

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', 

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download