python-mysqlHow do I insert a date into a MySQL database using Python?
To insert a date into a MySQL database using Python, the following steps can be followed:
- Import the necessary packages:
import mysql.connector from datetime import datetime
- Establish a connection to the MySQL database:
mydb = mysql.connector.connect( host="localhost", user="user", passwd="passwd", database="mydatabase" )
- Create a cursor object and use it to execute a query:
mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address, date_of_birth) VALUES (%s, %s, %s)"
- Create a date object in the desired format:
date_of_birth = datetime.strptime('1995-10-12', '%Y-%m-%d').date()
- Pass the date object as a parameter to the query:
val = ("John", "Highway 21", date_of_birth) mycursor.execute(sql, val)
- Commit the changes to the database:
mydb.commit()
- Print a success message:
print(mycursor.rowcount, "record inserted.")
Output: 1 record inserted.
Code explanation
**
- Import the necessary packages: This imports the
mysql.connector
package, which is used to connect to the MySQL database, and thedatetime
package, which is used to create a date object in the desired format. - Establish a connection to the MySQL database: This creates a connection to the MySQL database using the given credentials.
- Create a cursor object and use it to execute a query: This creates a cursor object, which is used to execute SQL queries, and a query that inserts a date into the database.
- Create a date object in the desired format: This creates a date object in the desired format using the
datetime.strptime()
method. - Pass the date object as a parameter to the query: This passes the date object as a parameter to the query.
- Commit the changes to the database: This commits the changes to the database.
- Print a success message: This prints a success message after the changes have been committed.
## Helpful links
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to show the MySQL processlist?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I connect Python to a MySQL database using Visual Studio Code?
- How can I use a while loop in Python to interact with a MySQL database?
- How do I use Python to update multiple columns in a MySQL database?
See more codes...