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 do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I connect Python to a MySQL database using an Xserver?
- How can I troubleshoot a Python MySQL OperationalError?
- How do I check the version of MySQL I am using with Python?
- How do I use Python to handle MySQL NULL values?
See more codes...