top of page
back.jpg
crystgandhi

Python MySQL Database Operations Example with mysql.connector



import mysql.connector

try:
    # Establish a connection to the MySQL database
    con = mysql.connector.connect(host="localhost", port=3306, user="username", password="password", database="Education")

    # Create a cursor to execute SQL queries
    cursor = con.cursor()

    # Insert records into the "student" table
    cursor.execute("INSERT INTO student VALUES('Eliza', 104)")
    cursor.execute("INSERT INTO student VALUES('Kattie', 105)")
    cursor.execute("INSERT INTO student VALUES('Jack', 106)")

    # Execute a SELECT query to retrieve all records from the "student" table
    cursor.execute("SELECT * FROM student")

    # Print the results of the SELECT query
    for r in cursor:
        print(r[0], r[1])

    # Commit the changes to the database
    con.commit()

except mysql.connector.Error as e:
    print("Connection Unsuccessful:", e)

finally:
    # Close the cursor and connection in the finally block to ensure proper cleanup
    cursor.close()
    con.close()

1 view0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page