Adding a record to the table
The INSERT INTO statement is used to add a record to the table. In python, we can mention the format specifier (%s) in place of values.
We provide the actual values in the form of tuple in the execute() method of the cursor.
Consider the following example.
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"
7.
8. #The row values are provided in the form of tuple
9. val = ("John", 110, 25000.00, 201, "Newyork")
10.
11. try:
12. #inserting the values into the table
13. cur.execute(sql,val)
14.
15. #commit the transaction
16. myconn.commit()
17.
18. except:
19. myconn.rollback()
20.
21. print(cur.rowcount,"record inserted!")
22. myconn.close()
Output:
1 record inserted!
Insert multiple rows
We can also insert multiple rows at once using the python script. The multiple rows are mentioned as the list of various tuples.
Each element of the list is treated as one particular row, whereas each element of the tuple is treated as one particular column value (attribute).
Consider the following Statement
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")
5. #creating the cursor object
6. cur = myconn.cursor()
7. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"
8. val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of spain"),("Nick",104,90000.00,201,"Newyork")]
9.
10. try:
11. #inserting the values into the table
12. cur.executemany(sql,val)
13.
14. #commit the transaction
15. myconn.commit()
16. print(cur.rowcount,"records inserted!")
17.
18. except:
19. myconn.rollback()
20.
21. myconn.close()
Output:
3 records inserted!
Row ID
In SQL, a particular row is represented by an insertion id which is known as row id. We can get the last inserted row id by using the attribute lastrowid of the cursor object.
Consider the following example.
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6.
7. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"
8.
9. val = ("Mike",105,28000,202,"Guyana")
10.
11. try:
12. #inserting the values into the table
13. cur.execute(sql,val)
14.
15. #commit the transaction
16. myconn.commit()
17.
18. #getting rowid
19. print(cur.rowcount,"record inserted! id:",cur.lastrowid)
20.
21. except:
22. myconn.rollback()
23.
24. myconn.close()
Output:
1 record inserted! Id: 0


0 Comments