Ben Ben - 5 months ago 19
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')
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.

Answer

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.

Comments