2.8 KiB
2.8 KiB
C1 - MySQL Connectivity
Problem Statement: Implement MYSQL/Oracle database connectivity with PHP /python /Java Implement Database navigation operations (add, delete, edit,).
Pre-requisites (with installation command for Ubuntu):
- Python3 -
sudo apt install python3
- pip -
sudo apt install pip
- mysql-connector -
pip3 install mysql-connector
ORpip3 install mysql-connector --break-system-packages
(installs it system-wide)
Instructions
- First, open the Terminal and log in to MySQL:
mysql -u root -p
Note
Usually the password in our labs is
root
. If you don't know the password, try runningsudo mysql
. This will run themysql
command as root.
- Whether you logged in as root or not, run this command to set the password for
root
user in mysql which is required for connecting to the database:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
FLUSH PRIVILEGES;
- Now, in MySQL we need to initialize the database and tables:
-- Creating the database
CREATE DATABASE connectMe;
USE connectMe;
-- Creating a table
CREATE TABLE students (
roll INT,
name VARCHAR(255)
);
-- Exit
exit
We need to
exit
from MySQL shell since the work there is done for now.
- Create a new file
connectSQL.py
with the following contents:
import mysql.connector
# Connecting to MySQL database
db = mysql.connector.connect(
host="localhost",
user="root",
password="root", # Password of root user we set in step 2
database="connectMe" # Name of the database we created in step 3
)
Cursor = db.cursor()
sqlInsert = "INSERT INTO students (roll, name) VALUES (21, 'Stewie')" # insert operation
Cursor.execute(sqlInsert)
print(Cursor.rowcount, "record added to database.")
Cursor.execute(sqlInsert)
sqlInsert = "INSERT INTO students (roll, name) VALUES (22, 'Foxy')" # insert operation
print(Cursor.rowcount, "record added to database.")
sqlUpdate = "UPDATE students SET roll = 21 WHERE roll = 20"
Cursor.execute(sqlUpdate)
print(Cursor.rowcount, "record updated.")
sqlDelete = "DELETE FROM students WHERE roll = 20"
Cursor.execute(sqlDelete)
print(Cursor.rowcount, "record deleted.")
db.commit()
Cursor.close()
db.close()
- Open Terminal and run the above program:
python3 connectSQL.py
Note
This step assume you have stored the file in home directory or you know how to change the current working directory.
- That's it! You can view the changes in MySQL by logging in using
mysql -u root -p
(Password:root
) and viewing the table:
USE connectMe;
SELECT * FROM students;
Warning
Never use
root
as password in production. Use a strong password. This guide usesroot
as password for simplicity and educational purposes.