Insert Operation

The INSERT INTO statement is used to add new rows to a table in a MySQL database. This section demonstrates how to insert data using Python.

  • Single Record Insert: Use the execute() method with a SQL query and a tuple of values.
  • Multiple Records Insert: Use the executemany() method with the same query and a list of tuples, where each tuple represents a row.
  • Commit Changes: Always call connection.commit() after INSERT operations to save the changes to the database.
  • Example

    
    import mysql.connector
    
    # Establishing a connection
    connection = mysql.connector.connect(
        host='localhost',
        user='root',
        password='yourpassword',
        database='student_db'
    )
    cursor = connection.cursor()
    
    # Inserting data into the 'students' table
    cursor.execute("INSERT INTO students (name, age, grade) VALUES ('Alice', 20, 'A')")
    cursor.execute("INSERT INTO students (name, age, grade) VALUES ('Bob', 22, 'B')")
    cursor.execute("INSERT INTO students (name, age, grade) VALUES ('Charlie', 21, 'A')")
    connection.commit()
    
    print("Data inserted successfully")
    
    cursor.close()
    connection.close()
                

    Output

    Data inserted successfully

    Data in 'students' Table After Insertion

    id name age grade
    1 Alice 20 A
    2 Bob 22 B
    3 Charlie 21 A