How do I insert a Python tuple into a MySQL database?

Assuming a MySQL database named test is present on the server and a table named employee is also created. The table has five fields: fname, lname, age, gender, and salary.

The tuple object containing the record data is defined as

 t1 = (`Mac`,` Mohan`, 20, `M`, 2000) 

To establish an interface between MySQL and Python 3, you need to install the PyMySQL module. You can then establish a connection using the following statements

< p>

 import PyMySQL # Open database connection db = PyMySQL.connect ("localhost", "root", " "," tes t ") # prepare a cursor object using cursor () method cursor = db.cursor ()  

The next step is to set up an insert query using the data in the tuple.

 sql = "insert into employee values ​​(% s, % s,% d,% s,% d) "% t1 

This request is now executed using the execute () method of the cursor object.

 cursor.execute (sql) 

If you check the contents of the employee table, it will show the new record added to it.

< / p>

Get Solution for free from DataCamp guru