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)
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()
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
Now, execute this query using the execute() method of the cursor object
cursor.execute(sql)
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!