在建表的类中定义时间戳类型的column时,应写成:
d_time = db.Column(db.DateTime, nullable=False)
向MySQL数据库中插入数据时,插入数据的类型和格式(以当前系统时间为例)应写成如下形式:
d_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
此处需要import time
这样插入数据库中的数据格式就是这样的了:
附上在Flask项目中利用SQLAlchemy建表,插入数据,删表全部代码:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import time
import csv
import pymysql
pymysql.install_as_MySQLdb()
app = Flask(__name__)
# 配置数据库地址
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]/real_time_db'
# 跟踪数据库的修改,默认填False
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Fur(db.Model):
# 定义表名
__tablename__ = 'fur_data'
id = db.Column(db.Integer, primary_key=True)
current_A = db.Column(db.Float, nullable=False)
current_B = db.Column(db.Float, nullable=False)
current_C = db.Column(db.Float, nullable=False)
action_A = db.Column(db.Float, nullable=False)
action_B = db.Column(db.Float, nullable=False)
action_C = db.Column(db.Float, nullable=False)
d_time = db.Column(db.DateTime, nullable=False)
# 删除表
db.drop_all()
# 创建表
db.create_all()
reader = csv.reader(open('FMF_data.csv'))
# A,B,C电流和频率的list初始化
current_A_list = []
current_B_list = []
current_C_list = []
action_A_list = []
action_B_list = []
action_C_list = []
for list in reader:
current_A_list.append(list[0])
current_B_list.append(list[1])
current_C_list.append(list[2])
action_A_list.append(list[3])
action_B_list.append(list[4])
action_C_list.append(list[5])
len = len(current_A_list)
i = 0
# 每隔一秒插入一个数据
while True:
time.sleep(1)
current_A = current_A_list[i]
current_B = current_B_list[i]
current_C = current_C_list[i]
action_A = action_A_list[i]
action_B = action_B_list[i]
action_C = action_C_list[i]
d_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
fur = Fur(current_A=current_A, current_B=current_B, current_C=current_C, action_A=action_A, action_B=action_B, action_C=action_C, d_time=d_time)
db.session.add(fur)
db.session.commit()
print("插入成功!")
i += 1
if i == 3600:
i = 0
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
一个实时更新的数据库,每一秒插入一条数据,亲测可用!
完整代码的详细说明请参考我的另一篇博客:https://blog.csdn.net/xiecheng1995/article/details/92427868
本人原创。转载请标明出处,谢谢!