Write a python code to configure the mysql connector in your system and insert data to mysql table after which you fetch and display data from table:
Certainly! Below is a Python code example that demonstrates how to configure the MySQL connector, insert data into a MySQL table, and then fetch and display data from the table.
Make sure you have the mysql-connector-python
library installed. If not, you can install it using pip install mysql-connector-python
.

import mysql.connector
# Configure MySQL connection
config = {
"host": "localhost", # Replace with your MySQL host
"user": "your_username", # Replace with your MySQL username
"password": "your_password", # Replace with your MySQL password
"database": "your_database" # Replace with your MySQL database name
}

# Connect to MySQL
try:
connection = mysql.connector.connect(**config)
print("Connected to MySQL")
# Create a cursor
cursor = connection.cursor()
# Create a table if it doesn't exist
create_table_query = """
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT
)
"""
cursor.execute(create_table_query)

# Insert data into the table
insert_query = "INSERT INTO employees (name, age) VALUES (%s, %s)"
data_to_insert = [
("John Doe", 30),
("Jane Smith", 28),
("Michael Johnson", 35)
]
cursor.executemany(insert_query, data_to_insert)
connection.commit()
print("Data inserted into the table")

# Fetch and display data from the table
select_query = "SELECT id, name, age FROM employees"
cursor.execute(select_query)
rows = cursor.fetchall()
print("Fetched data from the table:")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
# Close the cursor and connection
if cursor:
cursor.close()
if connection:
connection.close()
print("MySQL connection closed")
Replace "localhost"
, "your_username"
, "your_password"
, "your_database"
with your actual MySQL server details. This code establishes a connection, creates a table if it doesn’t exist, inserts data into the table, fetches the data, and displays it.
Make sure your MySQL server is running before executing the code.