python-mysqlHow do I execute an INSERT statement in MySQL using Python?
To execute an INSERT statement in MySQL using Python, you must first import the MySQL Connector/Python module. This module provides an API for connecting to and working with MySQL databases.
Once the module is imported, you can establish a connection to the MySQL server. This can be done by creating a connection object using the connect()
method, and passing in the necessary parameters (host, database, user, and password).
After establishing a connection to the MySQL server, you can then create a cursor object. The cursor object is used to execute SQL statements on the database.
To execute an INSERT statement, you can use the execute()
method of the cursor object. This method takes the SQL statement as a parameter, and executes it on the database.
For example:
import mysql.connector
# Establish connection to MySQL server
conn = mysql.connector.connect(host="localhost", database="mydb", user="myuser", password="mypass")
# Create cursor object
cursor = conn.cursor()
# Execute INSERT statement
cursor.execute("INSERT INTO users (name, age) VALUES ('John', 25)")
# Commit changes to database
conn.commit()
This code will execute the INSERT statement on the database, which will add a new row to the users
table with the values John
and 25
.
Code explanation
import mysql.connector
: imports the MySQL Connector/Python moduleconn = mysql.connector.connect(host="localhost", database="mydb", user="myuser", password="mypass")
: establishes a connection to the MySQL servercursor = conn.cursor()
: creates a cursor objectcursor.execute("INSERT INTO users (name, age) VALUES ('John', 25)")
: executes an INSERT statement on the databaseconn.commit()
: commits changes to the database
Helpful links
More of Python Mysql
- How can I connect Python to a MySQL database?
- How can I connect Python and MySQL?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database using an Xserver?
- How do I connect Python with MySQL using XAMPP?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use Python to query MySQL with multiple conditions?
- How do I use a cursor to interact with a MySQL database in Python?
- How can I check the version of MySQL I'm using with Python?
- How do I use Python to update multiple columns in a MySQL database?
See more codes...