MySQL with Python


For Installation MYSQL Connector Run This Command:
 pip install mysql-connector-python

# Import the MySQL connector library to connect Python with MySQL
import mysql.connector as mysql  

# Establish a connection to the MySQL database
# Host where the database server is running (localhost means your own computer) # Username to access the database
# Password for the database user
# Name of the database to use
mydb = mysql.connect(          
  host="localhost",
  user="root",                  
  password="54321",            
  database="banks"              
)

# Create a cursor object to execute SQL queries
mycursor = mydb.cursor()        

# Execute an SQL query to select all records from the 'employee' table
mycursor.execute("SELECT * FROM employee")  

# Fetch all the results from the executed query and store them in 'myresult'
myresult = mycursor.fetchall()  

# Loop through each record in the result set
for x in myresult:              
  print(x)    # Print each record
# SQL query to insert a new record into 'employee' table
sql = "INSERT INTO employee  VALUES (%s, %s,%s,%s,%s)"
# Values to insert (id, name, job, date, salary) 
val = (7, "Raju","Doctor",'2025-07-01','20')            
# Execute the insert query with the provided values
mycursor.execute(sql, val)      
# Commit the transaction to save changes to the database
mydb.commit()                  
# Print how many records were inserted
print(mycursor.rowcount, "record inserted.")  

Post a Comment

Previous Post Next Post