Skip to content

How to Update a MySQL Table in Python

First, you will need the mysql.connector. If you are unsure of how to get this setup, refer to How to Install MySQL Driver in Python.

How to Update a MySQL Table in Python

import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "UPDATE customers SET address = 'Stoneleigh Place' WHERE address = 'Abbey Road'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) affected")
Code language: Python (python)

Prevent SQL Injection in your Update Clause in Python

import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() sql = "UPDATE customers SET address = %s WHERE address = %s" val = ("Stoneleigh Place", "Abbey Road") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record(s) affected")
Code language: Python (python)

See also  How to a Run Bash Command in Python
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x