python-mysqlHow do I insert the current datetime into a MySQL database using Python?
Using Python, you can insert the current datetime into a MySQL database by first creating a datetime object and then using the cursor.execute() method. The following example code block shows how to do this:
import mysql.connector
from datetime import datetime
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address, date_time) VALUES (%s, %s, %s)"
val = ("John", "Highway 21", datetime.now())
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Output example
1 record inserted.
The code can be broken down into the following parts:
- Import the
mysql.connectoranddatetimemodules. - Connect to the MySQL database.
- Create a
datetimeobject. - Create an SQL query with placeholders for the values.
- Execute the query with the
datetimeobject as one of the values. - Commit the changes to the database.
- Print the number of records inserted.
Helpful links
More of Python Mysql
- How can I create a web application using Python and MySQL?
- How do I connect Python with MySQL using XAMPP?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I connect Python to a MySQL database?
- How can I use a while loop in Python to interact with a MySQL database?
- How can I print the result of a MySQL query in Python?
- How do I check the version of MySQL I am using with Python?
- How do Python and MySQL compare to MariaDB?
- How do I use a Python variable in a MySQL query?
- How can I set a timeout for a MySQL connection in Python?
See more codes...