How to connect to MySQL using Python on Linux

In this article, we will see how to connect to MySQL using Python on Linux.In this article, we will connect to MySQL Server from python using mysql-connector. Connect to Python contains below steps.

1. Install mysql connector.
2. Create connection variable in python script file.
3. Execute command on MySQL Server using python script file.

Connection to MySQL using Python Steps:

Step1: Install mysql connector.

a. Open terminal
b. Then, execute “sudo apt-get install mysql-connector”

Step2: Create connection variable in python script file.

a. Create a file with the name connection.py
b. Enter the following lines in the connection.py Python file.

import mysql.connector mydb=mysql.connector.connect( host="localhost", user="root", passwd="admin@123", database="r2schools")

print(mydb)

c. Save this file.

Note: Indentation is must in Python scripting.
Where
mydb is the variable to connect to MySQL server using mysql-connector.
host is the name of host or ip
user is name of user who is having access to the MySQL server.
passwd is password of user.

d. If you dont the know the host name and user name, run the below command in MySQL Server.

select host,user from mysql.user

Step3. Execute command on MySQL Server using python script file.

1. Now command prompt as administrator.
2. Navigate to the connection.py location and run the below command.

python3 connection.py

or

python connection.py

Step4. If we want to get MySQL Server version using Python, then run below file.

import mysql.connector mydb=mysql.connector.connect( host="localhost", user="root", passwd="admin@123", database="r2schools") mycursor=mydb.cursor() mycursor.execute("SELECT VERSION()") row=mycursor.fetchone() print("Server Version is ",row[0])

Then, execute the connection.py again.

Leave a Reply

Your email address will not be published. Required fields are marked *