The UPDATE Statement The UPDATE statement is used to modify existing records in a table. You need to specify which columns you want to update and what the new values should be. The SET clause is used to define the new values for the columns, and the WHERE clause is used to specify which rows should be updated.
import mysql.connector
# Create the connection object
conn = mysql.connector.connect(
host="localhost",
user="root",
password="google",
database="PythonDB"
)
# Create the cursor object
cur = conn.cursor()
# Define the SQL query with UPDATE statement
query = "UPDATE Employee SET salary = %s WHERE id = %s"
# Define the new values and the condition
values = (60000, 1)
# Execute the query
cur.execute(query, values)
# Commit the changes
conn.commit()
# Check if the update was successful
print(f"Rows affected: {cur.rowcount}")
# Close the connection
cur.close()
conn.close()
The DELETE FROM Statement The DELETE FROM statement is used to remove records from a table. It's important to use the WHERE clause to specify which records to delete. If you omit the WHERE clause, all records in the table will be deleted.
import mysql.connector
# Create the connection object
conn = mysql.connector.connect(
host="localhost",
user="root",
password="google",
database="PythonDB"
)
# Create the cursor object
cur = conn.cursor()
# Define the SQL query with DELETE statement
query = "DELETE FROM Employee WHERE id = %s"
# Define the condition for deletion
values = (1,)
# Execute the query
cur.execute(query, values)
# Commit the changes
conn.commit()
# Check if the deletion was successful
print(f"Rows affected: {cur.rowcount}")
# Close the connection
cur.close()
conn.close()
1. Update Operation: Use the UPDATE statement to modify existing records. Specify the columns to be updated and their new values, and use the WHERE clause to target specific rows.
2. Delete Operation: Use the DELETE FROM statement to remove records from a table. Use the WHERE clause to specify which records to delete. Without the WHERE clause, all records in the table will be removed.