python-mysqlHow do I insert data into a MySQL database using Python?
To insert data into a MySQL database using Python, use the PyMySQL library.
Example code
import pymysql
# Open database connection
db = pymysql.connect("localhost","user","password","database" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
This code will insert a record into the EMPLOYEE table in the database. The record will contain the values 'Mac', 'Mohan', 20, 'M', and 2000 for the columns FIRST_NAME, LAST_NAME, AGE, SEX, and INCOME respectively.
Code explanation
import pymysql
: imports the PyMySQL librarydb = pymysql.connect("localhost","user","password","database" )
: opens a connection to the MySQL databasecursor = db.cursor()
: creates a cursor object to execute queriessql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', '%d', '%c', '%d' )" % \ ('Mac', 'Mohan', 20, 'M', 2000)
: prepares the SQL query to insert a record into the EMPLOYEE tablecursor.execute(sql)
: executes the prepared SQL querydb.commit()
: commits the changes to the databasedb.rollback()
: rolls back the changes in case of an errordb.close()
: closes the connection to the database
Helpful links
More of Python Mysql
- How can I connect Python to a MySQL database?
- How do I use Python to authenticate MySQL on Windows?
- How can I use Python to retrieve data from MySQL?
- How do I use Python to connect to a MySQL database using XAMPP?
- How can I create a Python MySQL tutorial?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Yum to install the MySQLdb Python module?
- How can I use Python and MySQL to generate a PDF?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How can I use Python to interact with a MySQL database using YAML?
See more codes...