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”.
import mysql.connectorEstablish database connection
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”test_db”
)Initialize cursor
mycursor = mydb.cursor()
Read from table
mycursor.execute(“SELECT * FROM test_table”)
myresult = mycursor.fetchall()
for x in myresult:
print(x)Write into table
sql = “INSERT INTO test_table (column1, column2) VALUES (%s, %s)”
val = (“value1”, “value2”)
mycursor.execute(sql, val)Commit the transaction
mydb.commit()
print(mycursor.rowcount, “record inserted.”)
You’ll need to replace "localhost"
, "yourusername"
, "yourpassword"
, "test_db"
, "test_table"
, "column1"
, "column2"
, "value1"
, and "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:
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.