Lokang 

Python and MySQL

python mysql update

To update data in a MySQL database using Python, you can modify the SQL UPDATE statement that you execute using the "mysql-connector-python" library. Here are the steps to update data in a MySQL database using Python:

Install the mysql-connector-python library using pip. You can use the following command to install it:

pip install mysql-connector-python

Import the mysql.connector module in your Python script. You can do this using the following code:

import mysql.connector

Establish a connection to your MySQL server using the mysql.connector.connect() method. This method takes several parameters, including the host name, user name, password, and database name. Here is an example:

mydb = mysql.connector.connect(
 host="localhost",
 user="yourusername",
 password="yourpassword",
 database="mydatabase"
)

Once you have established a connection, you can create a new cursor object using the connection object and execute an SQL UPDATE statement to update data in a table. Here is an example:

mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 37'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")

In this example, we are updating the "address" column in the "customers" table to be "Canyon 123" where the current value of the "address" column is "Highway 37". The SQL statement to update a table is "UPDATE" followed by the name of the table, followed by the "SET" keyword and the column name and new value, followed by the "WHERE" keyword and the condition that determines which rows to update.

After executing the SQL statement, we commit the changes using the commit() method of the connection object. Finally, we print out the number of records that were affected.

The complete Python code to update data in a MySQL database using mysql-connector-python would look like this:

import mysql.connector
mydb = mysql.connector.connect(
 host="localhost",
 user="yourusername",
 password="yourpassword",
 database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 37'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")

In this code, you will need to replace "yourusername" and "yourpassword" with the actual values for your MySQL server, and "mydatabase" with the name of your database. Once you run this code, it will update the "address" column in the "customers" table where the current value of the "address" column is "Highway 37", and print out the number of records that were affected.