This repository has been archived on 2024-09-30. You can view files and clone it, but cannot push or open issues/pull-requests.
adbMonitor/database.py

124 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import pymysql
import modules.read_config
import json
import logging
# 创建表
create_table_sql = """CREATE TABLE devicesinfo (id INT AUTO_INCREMENT PRIMARY KEY,device VARCHAR(100),time JSON);"""
# 为device创建索引
create_idx_device = """CREATE INDEX idx_device ON devicesinfo (device);"""
# 连接到 MySQL 数据库
def connect_to_mysql():
db_host = modules.read_config.read_config_ini()['host']
db_user = modules.read_config.read_config_ini()['username']
db_passwd = modules.read_config.read_config_ini()['password']
db_dbname = modules.read_config.read_config_ini()['database_name']
try:
conn = pymysql.connect(
host=db_host, # 数据库主机名或IP地址
user=db_user, # 数据库用户名
password=db_passwd, # 数据库密码
database=db_dbname # 数据库名
)
print("成功连接到 MySQL 数据库!")
return conn
except pymysql.Error as e:
print(f"连接到数据库时出现错误:{e}")
return None
# 创建表
def create_table(sql):
connection = connect_to_mysql()
try:
with connection.cursor() as cursor:
cursor.execute(sql)
# 提交事务
connection.commit()
print("成功创建表!")
except pymysql.Error as e:
print(f"创建表时出现错误:{e}")
connection.close()
def query_table(device):
connection = connect_to_mysql()
try:
with connection.cursor() as cursor:
# 使用参数化查询来查询设备信息
sql = "SELECT * FROM devicesinfo WHERE device = %s"
cursor.execute(sql, (device,))
result = cursor.fetchone()
# print(f"result:{result},type:{type(result)}")
if result:
device_info = {
'id': result[0],
'device': result[1],
'time': result[2]
}
print(f"查询结果:{device_info}\n类型:{type(device_info)}")
return device_info
else:
print("设备不存在。")
return False
except pymysql.Error as e:
print(f"查询设备信息时出现错误:{e}")
logging.ERROR(e)
connection.close()
def add_device(device,time):
connection = connect_to_mysql()
try:
with connection.cursor() as cursor:
# 使用参数化查询来插入数据
sql = "INSERT INTO devicesinfo (device, time) VALUES (%s, %s)"
cursor.execute(sql, (device, time))
# 提交事务
connection.commit()
print("成功插入数据!")
except pymysql.Error as e:
print(f"插入数据时出现错误:{e}")
connection.close()
def update_time(device, new_time):
connection = connect_to_mysql()
try:
with connection.cursor() as cursor:
# 使用 JSON_SET 函数更新 'time' 字段
sql = "UPDATE devicesinfo SET time = %s WHERE device = %s"
cursor.execute(sql, (new_time, device))
# 提交事务
connection.commit()
print("成功更新设备的时间设备ID为:", device)
except pymysql.Error as e:
print(f"更新设备ID为 {device} 的时间时出现错误:{e}")
connection.close()
def main(device,new_time):
result = query_table(device)
if result:
print(f"time:{result['time']}\ntime类型{type(result['time'])}")
if new_time != result['time']:
update_time(device,new_time)
return
else:
print(f"time字段等于设备最新数据不更新数据库")
return
else:
add_device(device,new_time)
return