sTr8_Struggin sTr8_Struggin - 6 months ago 17
SQL Question

Connecting to a database with MySQLdb in python

So Basically I was just trying to test this out:

import MySQLdb

conn = MySQLdb.connect(host="myhost.com", user="myusername", passwd="mypassword", db="nameofmydatabase")

query = "INSERT INTO nameofmydatabase (columntitle) values ('sampletext')"
x = conn.cursor()
x.execute(query)
row = x.fetchall()


So this is the error that I got. I changed my actual info in the error but I was wondering how to fix this.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "write2MySQL_test.py", line 3, in <module>
conn = MySQLdb.connect(host="myhost.com", user="myusername", passwd="mypassword", db="nameofmydatabase")
File "/usr/local/lib/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 193, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'myhost.com' (60)")

Answer

Have you tried connecting to your MySQL database manually? (Using PhpMyAdmin or MySQL query browser etc) Are you able to reach the database from teh machine you are running the code on ? Ping the ip to see if there is a firewall.

Also, I am not sure how you set it up, is myhost.com pointing to something? Did you mean localhost?

Edit-

Try using your port like this

db = MySQLdb.connect(
    host = 'localhost', 
    user = 'root', 
    passwd = '', 
    db = 'dbname', 
    port = 3306)

I am not sure if your database is called "nameofmydatabase" so please make sure you fill the fields appropriately.