Fix: ‘pymysql.err.OperationalError: (2003 ‘ on Ubuntu 16.04

I’ve been learning web scraping with Python, and try using pymysql package.
Here’s the script:

import pymysql
# connect with mysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock',
					user='root', passwd='02390128', db='mysql')
cur = conn.cursor()
cur.execute("USE scraping;")
cur.execute("SELECT * FROM pages WHERE id=1")
print(cur.fetchone())
cur.close()
conn.close()

I run this script through terminal command:

python xxx.py

and getting this error:

Traceback (most recent call last):
  File "ConnectMYSQL.py", line 4, in <module>
    user='root', passwd=None, db='mysql')
  File "/home/loctv/Documents/Python/WebCrawling/scarpingEnv/local/lib/python2.7/site-packages/PyMySQL-0.6.2-py2.7.egg/pymysql/__init__.py", line 88, in Connect
    return Connection(*args, **kwargs)
  File "/home/loctv/Documents/Python/WebCrawling/scarpingEnv/local/lib/python2.7/site-packages/PyMySQL-0.6.2-py2.7.egg/pymysql/connections.py", line 626, in __init__
    self._connect()
  File "/home/loctv/Documents/Python/WebCrawling/scarpingEnv/local/lib/python2.7/site-packages/PyMySQL-0.6.2-py2.7.egg/pymysql/connections.py", line 818, in _connect
    2003, "Can't connect to MySQL server on %r (%s)" % (self.host, e))
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 2] No such file or directory)")

Here’s my way to fix this shit:
I figured out that the reason is not because MySQL server cannot connect on ‘127.0.0.1’, the reason is the socket name, which is ‘/tmp/mysql.sock’ is wrong.
To fix this, type this command in terminal

mysqladmin -u root -p variables | grep socket

Then enter your password
This is what I get:

screenshot-from-2017-02-09-17-19-04

As you can see, the socket name is not ‘/tml/mysql.sock’, it is ‘/var/run/mysqld/mysqld.sock’
So I copy that name, and change the script into:

import pymysql
# connect with mysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/var/run/mysqld/mysqld.sock',
					user='root', passwd='02390128', db='mysql')
cur = conn.cursor()
cur.execute("USE scraping;")
cur.execute("SELECT * FROM pages WHERE id=1")
print(cur.fetchone())
cur.close()
conn.close()

Notice that this is one of the many solutions to fix this, it’s just that this works for me. So if you get into the same issue, and still not be able to fix it, let’s try this out.

Advertisements