Here’s a Python code example that demonstrates how to configure the MySQL Connector, insert data into a MySQL table, and then fetch and display the data from the table. Before running the code, make sure you have the mysql-connector-python
package installed. You can install it using pip
pip install mysql-connector-python
Here’s the code:
import mysql.connector
# Configure MySQL connection
db_config = {
“host”: “localhost”,
“user”: “your_username”,
“password”: “your_password”,
“database”: “your_database”
}
# Create a connection
connection = mysql.connector.connect(**db_config)
cursor = connection.cursor()
# Create a table if it doesn’t exist
create_table_query = “””
CREATE TABLE IF NOT EXISTS example_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT
)
“””
cursor.execute(create_table_query)
connection.commit()
# Insert data into the table
insert_query = “INSERT INTO example_table (name, age) VALUES (%s, %s)”
data_to_insert = [
(“Alice”, 25),
(“Bob”, 30),
(“Carol”, 22)
]
cursor.executemany(insert_query, data_to_insert)
connection.commit()
# Fetch and display data from the table
select_query = “SELECT * FROM example_table”
cursor.execute(select_query)
data = cursor.fetchall()
print(“Fetched data:”)
for row in data:
print(“ID:”, row[0])
print(“Name:”, row[1])
print(“Age:”, row[2])
print(“———–“)
# Close the cursor and connection
cursor.close()
connection.close()
Replace "your_username"
, "your_password"
, and "your_database"
with your actual MySQL credentials and database name. This code establishes a connection to MySQL, creates a table if it doesn’t exist, inserts data into the table, fetches the data, and then displays it.