Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to insert a Python object in MySQL?
Assuming that a MySQL database named 'test' is present on the server and a table named employee is also created. Let the table have five fields fname, lname, age, gender, and salary.
Suppose we want to insert a tuple object containing data of a record defined as follows 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 this query is executed using execute() method of the cursor object
cursor.execute(sql)
If you check the contents of the employee table, it will show a new record added to it.
Advertisements
