This blog post will explain how to update a row in a MySQL database table using python.
This is what the database table will look like.
| id | name |
| 1 | larry |
| 2 | curly |
| 3 | moe |
The mysql.connector library has to be imported so the program can update a database table row.
import mysql.connector
The two variables r1 and r2 are declared with certain data to help with the update query.
r1 = "david"
r2 = 1
A database connection is setup to receive the query.
sql = mysql.connector.connect(
host="localhost",
user="user",
password="pass",
database="somedatabase"
)
A cursor is defined to traverse the rows of a database table.
cursor = sql.cursor()
The statements below perform the update query.
query = f"UPDATE names SET name = '{r1}' WHERE id = '{r2}'"
cursor.execute(query)
sql.commit()
The statements below will retrieve the updated rows in the table.
query = "SELECT * FROM names"
cursor.execute(query)
rows = cursor.fetchall()
The result is printed to the screen.
for row in rows:
print(row)
The statements below destroy the cursor and terminate the database connection.
cursor.close()
sql.close()
This is what the whole source code looks like.
import mysql.connector
r1 = "david"
r2 = 1
sql = mysql.connector.connect(
host="localhost",
user="user",
password="pass",
database="somedatabase"
)
cursor = sql.cursor()
query = f"UPDATE names SET name = '{r1}' WHERE id = '{r2}'"
cursor.execute(query)
sql.commit()
query = "SELECT * FROM names"
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.close()
sql.close()
