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.connector
anddatetime
modules. - Connect to the MySQL database.
- Create a
datetime
object. - Create an SQL query with placeholders for the values.
- Execute the query with the
datetime
object 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 use Python to retrieve data from MySQL?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I use Python to query MySQL with multiple conditions?
- How can I use Python to make a MySQL request?
- How can I use Python to interact with a MySQL database using YAML?
- How can I connect Python to a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How can I connect to MySQL using Python?
- How do I connect to a MySQL database using XAMPP and Python?
- How do I use Python and MySQL to convert fetchall results to a dictionary?
See more codes...