Home > other >  Unable to access MysqlDB using SQL Alchemy
Unable to access MysqlDB using SQL Alchemy

Time:01-03

I have a question, when I'm using the sqlalchemy package to connect MySQL connection with the mentioned code it says, " No module named 'MySQLdb'". At the same time, I can able to connect PostgreSQL with a similar code. Do I need to install the MysqlDb package for sqlalchemy?.

For reference, I do have MySQL-connector as an alternate package on my server

from sqlalchemy import create_engine

# DEFINE THE DATABASE CREDENTIALS
user = ''
password = ''
host = ''
port = 3306
database = ''

# PYTHON FUNCTION TO CONNECT TO THE MYSQL DATABASE AND
# RETURN THE SQLACHEMY ENGINE OBJECT
def get_connection():
        return create_engine(
                url="mysql://{0}:{1}@{2}:{3}/{4}".format(
                        user, password, host, port, database
                )
        )


if __name__ == '__main__':

        try:

                # GET THE CONNECTION OBJECT (ENGINE) FOR THE DATABASE
                engine = get_connection()
                print(
                        f"Connection to the {host} for user {user} created successfully.")
        except Exception as ex:
                print("Connection could not be made due to the following error: \n", ex)

CodePudding user response:

You need to specify in the connect string the connector. See the documentation:

https://docs.sqlalchemy.org/en/20/dialects/mysql.html#module-sqlalchemy.dialects.mysql.mysqlconnector

Connect String:

mysql mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>

If you don't specify mysqlconnector then SQLAlchemy seems to default to the MySQLdb connector. If you want to use a different connector, this is fine, but you need to specify it in the connect string.

  • Related