How to prevent pymysql (or mysql.connector) resolving localhost to IPv6?

60 Views Asked by At

I am trying to connect to MySQL from Python on my hosting provider's server. I have my database created, I can connect to it through SSH and with PHP. When I try to connect using Python I get an error Access denied for user 'user_name'@'::1' (using password: YES).

I reckon it might be due to Python resolving localhost to IPv6. I probably do not have access rights for my user on [::1] nor 127.0.0.1, only on localhost. Is it possible to prevent this behaviour?

If not than what can I try or what should I ask my hosting for to connect to database?

I tried both pymysql and mysql.connector with the same results.

I tried changing host to 127.0.0.1 or [::1]. My hosting specifically says that I should connect with localhost.

My short test script:

import os
import sys
import pymysql
pymysql.install_as_MySQLdb()
import mysql.connector


sys.path.insert(0, os.path.dirname(__file__))


def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    message = 'It works!\n'
    version = 'Python v' + sys.version.split()[0] + '\n'
    
    conn_message = ''
    
    
    conn = mysql.connector.connect(host='localhost', user='user_name', password='password', database='db_name', port=3306)
    # conn = pymysql.connect(host='localhost', user='user_name', passwd='password', db='db_name', port=3306)
    
    if conn:
        conn_message = 'MySQL: Yes :)'
    else:
        conn_message = 'MySQL: No :('

    conn.close()

    response = '\n'.join([message, version, conn_message])
    return [response.encode()]

1

There are 1 best solutions below

0
nbk On

You can update the user table with

UPDATE mysql.user SET host = 'localhost' WHERE user = 'user_name'

localhost would first try to open a socket, but then would try to open an tco/ip connection.

but it seems that your provides doesn't allow tcp/ip connections.