To insert a new student into Student table using Python/MySQL:

·        When using Python to insert a new student tuple into the Student table in a MySQL database, both the SQL command and the values must be provided to the execute( ) function. Shown in Figure 1 is a sample function that does just that.The screen output of running that function is shown in Figure 2.

 

Figure 1: Sample function of inserting into a table

def insertStudent():

    print("you have selected menu option 6") # Simulate function output.

    if connection.is_connected():

       db_Info = connection.get_server_info()

       print("Connected to MySQL Server version ", db_Info)

       global cursor

       cursor = connection.cursor(dictionary=True) #set dictionary to True

       cursor.execute("select database();")

       record = cursor.fetchone()

       print("You're connected to database: ", record)

       stuId = input("student id? ")    

       fname = input("first name? ")    

       lname = input("last name? ")

       major = input("major? ")   

       minor = input("minor? ")   

       credits = input("number of completed credits? ")  

       advisor = input("advisor's id? ")

       query = "insert into student values (%s,%s,%s,%s,%s,%s,%s)"

       values = (stuId,fname,lname,major,minor,credits,advisor)

       cursor.execute(query,values)

       connection.commit() #Commit the changes to the database. This is required to keep the changes.

    input("Press Enter to Continue\n")

    #system('cls')  # clears stdout

 

 

Figure 2: Screen output of getting student data and insert the new student into the Student table

 

References:

·        https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html