python-mysqlHow do I insert a datetime value into a MySQL database using Python?
To insert a datetime value into a MySQL database using Python, use the MySQL Connector/Python
library. The following example code creates a connection to a MySQL database, inserts a datetime value, and then prints the value in the database:
import mysql.connector
# Create connection to MySQL database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
# Create cursor object
mycursor = mydb.cursor()
# Create SQL statement
sql = "INSERT INTO customers (name, datetime_field) VALUES (%s, %s)"
val = ("John", "2020-02-20 10:45:00")
# Execute SQL statement
mycursor.execute(sql, val)
# Commit changes to database
mydb.commit()
# Print the inserted datetime value
print(mycursor.rowcount, "record inserted.")
# Print the value from the database
sql = "SELECT datetime_field FROM customers WHERE name=%s"
val = ("John",)
mycursor.execute(sql, val)
result = mycursor.fetchone()
print("Datetime value in database:", result[0])
Output example
1 record inserted.
Datetime value in database: 2020-02-20 10:45:00
The code consists of the following parts:
- Import the
mysql.connector
library. - Create a connection to the MySQL database.
- Create a cursor object.
- Create a SQL statement to insert the datetime value into the database.
- Execute the SQL statement.
- Commit the changes to the database.
- Print the number of records inserted.
- Create a SQL statement to select the datetime value from the database.
- Execute the SQL statement.
- Fetch the result.
- Print the datetime value from the database.
Helpful links
More of Python Mysql
- How can I host a MySQL database using Python?
- How can I use Python and MySQL to create a login system?
- How can I connect Python and MySQL?
- How can I connect Python to a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I access MySQL using Python?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
- How do I connect to a MySQL database using XAMPP and Python?
See more codes...