To write data to a MySQL database using Python, you can use the mysql-connector-python
library. Here’s an example code
import mysql.connector # Connect to the MySQL database cnx = mysql.connector.connect( host='your_host', user='your_user', password='your_password', database='your_database' ) # Create a cursor object cursor = cnx.cursor() # Define the data you want to insert data = ('John Doe', 30, '[email protected]') # Execute an INSERT query query = "INSERT INTO your_table (name, age, email) VALUES (%s, %s, %s)" cursor.execute(query, data) # Commit the changes cnx.commit() # Close the cursor and connection cursor.close() cnx.close()
In this example, replace 'your_host'
, 'your_user'
, 'your_password'
, and 'your_database'
with the actual connection details for your MySQL database.
The code establishes a connection to the MySQL database using the specified host, username, password, and database name. It then creates a cursor object to execute SQL queries.
The example defines the data you want to insert into the table as a tuple (data
). The %s
placeholders in the INSERT query represent the values to be inserted.
The code executes the INSERT query using the execute()
method, passing the query and the data tuple as parameters.
Finally, the changes are committed to the database using cnx.commit()
, and the cursor and connection are closed to release the resources.
Make sure to have the mysql-connector-python
library installed before running this code. You can install it using pip:
pip install mysql-connector-python
Remember to handle any exceptions that may occur during the database connection or query execution for proper error handling.