python-mysqlHow do I add a row to a MySQL database using Python?
To add a row to a MySQL database using Python, you can use the cursor.execute()
method. This method takes a SQL query as an argument and executes it. The following example code will add a row to a table called 'users' in a MySQL database:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
# Create a cursor object
mycursor = mydb.cursor()
# Create a SQL query
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
val = ("John", "[email protected]")
# Execute the query
mycursor.execute(sql, val)
# Commit the changes to the database
mydb.commit()
# Print the number of rows affected
print(mycursor.rowcount, "record inserted.")
Output example
1 record inserted.
The code consists of the following parts:
import mysql.connector
- imports the mysql connector library to allow Python to communicate with MySQL databases.mydb = mysql.connector.connect(...)
- establishes a connection to the MySQL database.mycursor = mydb.cursor()
- creates a cursor object which is used to execute queries.sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
- creates a SQL query which will insert a row into the 'users' table.val = ("John", "[email protected]")
- defines the values to be inserted into the table.mycursor.execute(sql, val)
- executes the SQL query with the given values.mydb.commit()
- commits the changes to the database.print(mycursor.rowcount, "record inserted.")
- prints the number of rows affected.
Helpful links
More of Python Mysql
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How do I connect to a MySQL database using XAMPP and Python?
- How can I host a MySQL database using Python?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
- How do I use Python to authenticate MySQL on Windows?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to access MySQL binlogs?
See more codes...