#Installing MySQL on Python :!pip install pymysql!pip install mysqlclient
1) Database Connection :
import mysql.connector# Establishing connection with the SQL dataBase = mysql.connector.connect( host ="localhost", user ="root", password ="sahil123", auth_plugin='mysql_native_password', port=3306)# Cursor to the database cursor = dataBase.cursor()cursor.execute("CREATE DATABASE Student")print("Student Data base is created")
Student Data base is created
2) Creating Database Table :
import mysql.connector # connecting to the database dataBase = mysql.connector.connect( host ="localhost", user ="root", passwd ="sahil123", database ="Student" )# preparing a cursor object cursorObject = dataBase.cursor()# creating table studentRecord ="""CREATE TABLE NEWSTUDENT ( NAME VARCHAR(20) NOT NULL, ROLL INT NOT NULL )"""# table created cursorObject.execute(studentRecord)
print("Displaying NAME and ROLL columns from the STUDENT table:")# selecting query query ="SELECT NAME, ROLL FROM NEWSTUDENT"cursorObject.execute(query)myresult = cursorObject.fetchall()for x in myresult:print(x)
Displaying NAME and ROLL columns from the STUDENT table:
('Ram', 85)
('Ram', 85)
('Akash', 98)
('Neel', 23)
('Rohan', 43)
('Amit', 87)
('Anil', 45)
('Megha', 55)
('Sita', 95)
6) Update Operation :
# drop clause statement ="UPDATE NEWSTUDENT SET ROLL = 23 WHERE Name ='Rohan'"cursorObject.execute(statement)dataBase.commit()
Example -2:
# drop clause statement ="UPDATE NEWSTUDENT SET NAME = 'ROSHAN' WHERE Name ='Rohan'"cursorObject.execute(statement)dataBase.commit()
7) DELETE OPERATION :
query ="DELETE FROM NEWSTUDENT WHERE ROLL = 55"cursorObject.execute(query)dataBase.commit()