Connect to MySQL database using python

Question:

So I am having a super hard time connecting to a local database using the python mysql.connector module. MySQL Workbench screenshot

So I am trying to connect using the highlighted connection. I use the password abcdefghijkl to log into the SQL environment. I am trying to connect to a database named flight_school.

My python script looks like so.

import mysql.connector

mydb = mysql.connector.connect("localhost", "root", "abcdefghijkl", "flight_school")

print(mydb.is_connected())

This above code in the arguments in the following order i.e.

  • hostname = localhost,
  • user = ‘root’,
  • password = ‘abcdefghijkl’, and
  • database name = ‘flight_school’.

It’s just not working. I get the following error.
Image of the error

I would really appreciate some advice, please.

Asked By: chintan thakrar

||

Answers:

Check out SQL-Alchemy module, works wonders from my experience.

Answered By: Angry_Coder

Please read always the official documentation

Your cooenction stirng has to have this form(if you do it this way=

 mydb = mysql.connector.connect(
     host="localhost",
     user="root",
     passwd="testpaaword",
     database="testdb"
 )
Answered By: nbk

Please read always the official documentation: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html

import mysql.connector
from mysql.connector import errorcode, MySQLConnection

try:
    db_connection = MySQLConnection(user='root', password='', port='3306', database='your_database')
    print("Database connection made!")
except mysql.connector.Error as error:
    if error.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database doesn't exist")
    elif error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("User name or password is wrong")
    else:
        print(error)
else:
    db_connection.close()

cursor = db_connection.cursor()

sql = ("commands")
cursor.execute(sql)
Answered By: Samuel Calado
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.