python-mysqlHow do I use Python to execute a MySQL transaction?
Using Python to execute a MySQL transaction is a relatively straightforward process. The most basic approach is to use the MySQLdb
library as follows:
import MySQLdb
# Open database connection
db = MySQLdb.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 table_name (field1, field2) VALUES ('%s', '%s')" % (value1, value2)
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
# disconnect from server
db.close()
This code will open a connection to the MySQL database, create a cursor object, prepare an SQL query to insert a record, execute the query, commit the changes, and then close the connection.
Code explanation
import MySQLdb
- this imports theMySQLdb
library which provides the necessary functions to connect to and interact with the MySQL database.db = MySQLdb.connect("localhost","user","password","database" )
- this creates a connection to the MySQL database. The parameters are the host, user, password, and database name.cursor = db.cursor()
- this creates a cursor object which is used to interact with the database.sql = "INSERT INTO table_name (field1, field2) VALUES ('%s', '%s')" % (value1, value2)
- this prepares an SQL query to insert a record into the database.cursor.execute(sql)
- this executes the SQL query.db.commit()
- this commits the changes to the database.db.close()
- this closes the connection to the database.
For more information, see the MySQLdb documentation and the MySQL Tutorial.
More of Python Mysql
- How can I connect Python to a MySQL database?
- How can I connect to MySQL using Python?
- How can I convert data from a MySQL database to XML using Python?
- How can I use Python and MySQL to generate a PDF?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect Python and MySQL?
- How do I connect Python with MySQL using XAMPP?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I check the version of MySQL I am using with Python?
- How do I fix a bad MySQL handshake error in Python?
See more codes...