Python |
您所在的位置:网站首页 › 创建xml文件并写入数据库中的数据 › Python |
【需求】1. 在数据库中创建表,且能按时间自动创建新表 2. 数据写入数据库 3. 从数据库读取数据
1. 创建表,并自动更新
1 def Creat_Table(InitMySQL,tabel_name):
2 # 创建游标
3 cursor = InitMySQL.cursor()
4 sql = "create table if not exists " + tabel_name + "(dTime datetime not null comment '时间'," \
5 "dElectric_uA int not null comment '电流'," \
6 "dDistance int not null comment '距离'," \
7 "dWarning int not null comment '报警')"
8 # 打印sql
9 print(sql)
10 cursor.execute(sql)
11 # 关闭游标
12 cursor.close()
需要输入数据库的连接对象和表名称,sql根据表名称判断数据库中是否存在该表,如果存在则不会创建,不存在则创建新表 tabel_name 可以根据时间创建 2. 向数据库中写入数据根据创建的数据库中表的类型进行数据填充 1 def Write_to_MySQL(InitMySQL,tabel_name, CurrentTime, Electric_uA, Distance, WaringStatus): 2 # 创建游标 3 cursor = InitMySQL.cursor() 4 # #创建sql 5 # w_table_name = 'warning' + day_time 6 sql = 'insert into '+ tabel_name+ ' values (%s, %s, %s, %s)' 7 print(sql) 8 result = cursor.execute(sql,(CurrentTime, Electric_uA, Distance, WaringStatus)) 9 if result == 1: 10 pass 11 # print('添加成功!') 12 else: 13 print('添加数据失败!') 14 # 4. 操作成功提交事务 15 InitMySQL.commit() 16 # 关闭游标 17 cursor.close() 整体表的创建与数据输入![]() ![]() 测试的数据库结果: 3. 从数据库读取数据 1 """ 2 【函数功能】 读取数据库中最新的几分钟数据 3 【输入】 需要查询的table名称(也可以从JSON中读取) 4 【输出】 查找的数据列表 5 """ 6 def Read_from_Mysql(InitMySQL, sql_tabel_name): 7 # 从JSON中读取sql需要的参数 8 set_time = filejson['MysqlInit']['set_delaytime_min'] 9 now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 10 last_time = (datetime.datetime.now() - datetime.timedelta(minutes = set_time)).strftime("%Y-%m-%d %H:%M:%S") 11 # sql_tabel_name = filejson['MysqlInit']['sql_tabel_name'] 12 sql_distance_header = filejson['MysqlInit']['distance_header'] 13 sql_time_header = filejson['MysqlInit']['time_header'] 14 # 创建游标 15 cursor = InitMySQL.cursor() 16 sql = "SELECT " + sql_distance_header + " FROM " + sql_tabel_name + " WHERE " + sql_time_header \ 17 + "'" +last_time + "'" 18 # print(sql) 19 cursor.execute(sql) 20 # 获取该字段下的数据 21 result = cursor.fetchall() 22 # 关闭游标 23 cursor.close() 24 # 将数据转换成列表 25 new_distance= [] 26 for dis in result: 27 new_distance.append(dis[0]) 28 return new_distance 【重点】sql的字符串拼接中可以加入变量 时间需要用单引号引起来 园中有博主写的关于数据库,非常详细 可以参考 https://www.cnblogs.com/hackerer/p/11588717.html |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |