I'm trying to create a database thta reflects a customisable stock level for every 15 minute window for an entire year.
My database structure looks like this:
time_period | day | month | stock |
---|---|---|---|
00:00 | 1 | 1 | 20 |
00:15 | 1 | 1 | 15 |
.... | ... | ... | ... |
23:45 | 1 | 1 | 0 |
00:00 | 2 | 1 | 20 |
.... | ... | ... | ... |
23:45 | 31 | 12 | 0 |
So in total there would be 96 * 366 = 35,136 rows in this particular table that I want to insert. The time_period
increments every 15 minutes (96 slots per day) for 266 days of the year.
Are there any ways to easily insert this data using a mySQL query or a loop?
So far the best option I've come up with is to manually generate the data into a JSON or CSV file and then import to the DB FROM FILE
- it seems like there should be an easier way to do this though?
EDIT: Attempted using Recursive Common Table Expressions as suggested by a commenter. My DB is running mySQL 5.7 so unfortunately this isn't an option
It would be quicker and easier to write a script to just insert 35,040 rows in a loop:
import datetime
import mysql.connector
cnx = mysql.connector.connect(user='root', password='xxxxxxxx', database='test')
cursor = cnx.cursor(prepared=True)
stmt = """INSERT INTO MyTable SET t = %s"""
time = datetime.datetime(2023, 1, 1, 0, 0, 0)
end = datetime.datetime(2024, 1, 1, 0, 0, 0)
while time < end:
cursor.execute(stmt, (time,))
time += datetime.timedelta(minutes=15)
cnx.commit()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.