Inserting data in Mysql using Python

Inserting data in Mysql using Python

As you are aware of using mysql-connector in last tutorial Connect Python with MySql. Now we will learn, how to insert data in mysql using python basic commands. The step is quite similar to select data from table. The difference is only you have to create a insert query with place holders like query = “insert into emp(empcode,empname,job,mgr,sal, comm, deptno) values (%s, %s, %s, %s, %s, %s, %s)” and then you need to create a tuple of values like values = (234, ‘Ramesh’, ‘SalesOp’, 124, 56730, 234, 22). Once it is done just pass these two as parameter to execute() function of cursor like mycursor. execute (query, values). Lets see one complete example for inserting record in mysql using Python.

Example : Insert data in mysql using Python

The output will look like this-

1, ‘Akash’, ‘teacher’, 1, Decimal(‘20000’), Decimal(‘1200’), 1)
(2, ‘Suraj’, ‘teacher’, 2, Decimal(‘23000’), Decimal(‘1300’), 2)
(3, ‘Aman’, ‘prof’, 3, Decimal(‘30000’), Decimal(‘2000’), 4)
(234, ‘Ramesh’, ‘SalesOp’, 124, Decimal(‘56730’), Decimal(‘234’), 22)

Here 234-Ramesh is the new data inserted in the table.

0 thoughts on “Inserting data in Mysql using Python

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>