Home > Database > Mysql Tutorial > body text

How to insert Python objects in MySQL?

WBOY
Release: 2023-08-24 14:05:05
forward
1048 people have browsed it

How to insert Python objects in MySQL?

Assume that a MySQL database named 'test' exists on the server, and a table named employee is also created. Let this table have five fields: fname, lname, age, gender and salary.

Suppose we want to insert a tuple object containing the following record data into the Msql database.

t1=('Steven', 'Assange', 21, 'M', 2001)
Copy after login

To establish an interface between MySQL and Python 3, you need to install the PyMySQL module. Then you can set up the connection using the following statements

import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","root","","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
Copy after login

Next step is to set up the insert query using data in the tuple

sql="insert into employee values(%s,%s,%d,%s,%d)" %t1
Copy after login

Now, execute this query using the execute() method of the cursor object

cursor.execute(sql)
Copy after login

If you inspect the contents of the employee table, it will show that a new record has been added .

The above is the detailed content of How to insert Python objects in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!