Connecting python to my mysql server

Question:how do i connect my mysql server to python?

Current behavior:shows cant connect to mysql server

it should get connected and work properly

Repl link: https://replit.com/@thrillerpoint65/pythonmysql

import mysql.connector
import pandas as pd

# Establish a connection to the MySQL database (replace these with your actual database credentials)
db_config = {
    "host": "localhost",
    "user": "mysql.exe -u root -p",
    "password": "",
    "database": "luluva12",
}

try:
    con = mysql.connector.connect(**db_config)
    print("Connected to MySQL database")
    c = con.cursor()

    # Define the employee data
    empdata = {
        "empid": [101, 102, 103, 104, 105, 106],
        "ename": ["Sachin", "Vinod", "Lakhbir", "Anil", "Devinder", "UmaSelvi"],
        "Doj": [
            "2012-01-12",
            "2012-01-15",
            "2007-09-05",
            "2012-01-17",
            "2007-09-05",
            "2012-01-16",
        ],
    }

    # Create a DataFrame from the employee data
    df = pd.DataFrame(empdata)

    # Loop through the DataFrame to insert data into the MySQL database
    for index, row in df.iterrows():
        empid = row["empid"]
        ename = row["ename"]
        Doj = row["Doj"]
        c.execute(
            "INSERT INTO employee (empid, ename, Doj) VALUES (%s, %s, %s)",
            (empid, ename, Doj),
        )
        con.commit()
    # Close the cursor and the database connection
    c.close()
    con.close()

    print("Data transfer Successful")
except mysql.connector.Error as err:
    print(f"Error: {err}")

Try changing that to root (By the way, Replit uses Linux, not windows)

1 Like