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 can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How can I host a MySQL database using Python?
- How do I fix a bad MySQL handshake error in Python?
- How can I connect Python to a MySQL database using an Xserver?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python and MySQL?
See more codes...