Hanwool Codes RSS Tag Admin Write Guestbook
software Engineering/mysql (1)
2023-01-06 07:43:34

I would like to share how to connect MySQL by using Python script.

My Python version is 3.7.6.

 

1. Install mysql-connector-python

 

First, you need to install mysql-connector-python module. Install this module by using pip.

pip install mysql-connector-python

 

2. Setup Mysql 

 

To connect mysql, we need to set up couple things in advance.

I try to connect local mysql server(localhost). But you can change host ip address if you want.

I created user "testuser" and password "0000" with "mysql_native_password" authentical plugin.

You can easily create user below query. 

CREATE USER 'testuser'@'localhost' IDENTIFIED WITH mysql_native_password BY '0000';

 

So, the summary of my setup is here.

● host : localhost 
● user : testuser
● password : 0000
● authentication plugin : mysql_native_password

 

3. Connect Python to Mysql

So here is source code. I write one query to check connection. 

If you want to see more details about mysql.connector module. Please check this link.

import mysql.connector
from mysql.connector import (connection)

try :

    mydb = mysql.connector.connect(
      host="localhost",
      user="testuser",
      password="0000",
      auth_plugin='mysql_native_password'
    )

    # simple query to check mysql is connected.
    # list tables from world database
    sql_select_Query = "show tables from world"

    cursor = mydb.cursor()
    cursor.execute(sql_select_Query)
    records = cursor.fetchall()
    
    print('tables : ', records)

    # close mysql connection
    if mydb.is_connected():
        cursor.close()
        mydb.close()
        print("MySQL connection is closed")

except mysql.connector.Error as e:
    print("Error reading data from MySQL table", e)

 

If connection is success, you can see this result.

 

If connection is not worked, you can see error message. You can see one of error message below.

ERROR 1045 is one of error value When you enter an incorrect password or password for your database

 

 

If you have any question, please write a comment



Hanwool Codes. Designed by 코딩재개발.