0

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()
2
  • 1
    are you using "xx.xxx.xxx.x" as your ip? Commented Jan 11, 2021 at 17:00
  • Thanks for the comment @JamM.HernandezQuiceno. I wrote it that way out of paranoia, but it is a real address I am trying to connect to. Neither it is localhost, as I've seen quite a few related questions but were all about connecting to localhost and managing apache config files. In my case, access to the server works just great, I can access the db using the console and the original PHP file I 'converted' to python also connects fine. But whenever I try using the new script I stumble upon the same error warning. Commented Jan 12, 2021 at 15:27

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.