Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

Can't connect to Mysql server via Python (Error 111)

I've recently started learning python and coming from PHP I thought a great way to do so would be transforming php scripts into python. I started with the basics: dates, lists, arrays, functions... so I went to try basic mysql connection.

The issue came here, as every time I execute the script an exception is returned stating:

2003 (HY000): Can't connect to MySQL server on 'xx.xxx.xxx.x' (111)

Traceback (most recent call last): File "connections/connection.py", line 23, in accountingCursor = accountingDb.cursor() NameError: name 'accountingDb' is not defined

The funny thing is that the same connection seems to be working just fine when attemped from the php script. I don't really know what am I missing, but I've been following the official documentation from MySQL webpage and still no clue as to what could be wrong.

This is my attempt:

import mysql.connector
from mysql.connector import errorcode


try:
    accountingDb = mysql.connector.connect(
        host="xx.xxx.xxx.x",
        database="dbname",
        user="user",
        password="pswrd"
    )
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Error en usuario o contrase?a")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("No existe la Base de Datos")
    else:
        print(err)


accountingCursor = accountingDb.cursor()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

write localhost as the host and then try. Something like this

import mysql.connector

mydb = mysql.connector.connect(host="localhost",user="root",password="pass")
print(mydb)
mycursor=mydb.cursor()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...