example of a Python script that connects to a MySQL database, reads from a table, and writes into it using the
mysql-connector-python library. This script assumes the existence of a table named “test_table” within a database named “test_db”.
Establish database connection
mydb = mysql.connector.connect(
mycursor = mydb.cursor()
Read from table
mycursor.execute(“SELECT * FROM test_table”)
myresult = mycursor.fetchall()
for x in myresult:
Write into table
sql = “INSERT INTO test_table (column1, column2) VALUES (%s, %s)”
val = (“value1”, “value2”)
Commit the transaction
print(mycursor.rowcount, “record inserted.”)
You’ll need to replace
"value2" with your actual MySQL host, username, password, database name, table name, column names, and values, respectively.
Before running this script, make sure you have the
mysql-connector-python package installed. If not, you can install it using
pip install mysql-connector-python
This script is a basic example and doesn’t include error handling. In a production environment, you’ll want to include try-except blocks to handle possible exceptions.