将mysql的datetime类型数据,封装成json时遇到的问题

JDBC与JSON日期处理
本文介绍了如何在使用JDBC从数据库中获取日期时正确处理datetime类型的数据,并演示了将包含日期的对象转换为JSON格式的方法。特别关注了如何避免常见错误,确保日期格式的一致性和正确性。

1.首先,直接使用jdbc将数据取数据,注意使用getTimestamp,而不是getTime方法

//在数据库中的时间类型时datetime,在此处要通过getTimeStamp将值取出来

vo.setDepCreateTime(rs.getTimestamp(8));

2.直接调用JSONArray.fromObject(list),装换成JSON对象时,注意:如果list中的变量含有java.util.date对象时,则需要使用JSONConfig进行处理。JsonDateValueProcessor类的代码如下:

package util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class JsonDateValueProcessor implements JsonValueProcessor {
	private String pattern = "yyyy-MM-dd HH:mm:ss";

	//定义两个构造函数,通过第二个构造函数可以自定义时间格式化字符串
	public JsonDateValueProcessor() {
		super();
	}

	public JsonDateValueProcessor(String format) {
		this.pattern = format;

	}

	public Object processArrayValue(Object arg0, JsonConfig arg1) {
		// TODO Auto-generated method stub
		return process(arg0);
	}

	public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
		// TODO Auto-generated method stub
		return process(arg1);
	}
	private Object process(Object val){
		if(val instanceof Date&& val!=null){
			SimpleDateFormat sdf=new SimpleDateFormat(this.pattern,Locale.CHINESE);
			System.out.println("date format by valueProcess:"+sdf.format(val));
			return sdf.format(val);
		}else
			return val==null?"":val.toString();
		
	}

}

在jsonarray进行转换时,这样调用:

JsonConfig config = new JsonConfig();
config.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor());
arr=JSONArray.fromObject(result,config);

<think>我们参考了用户提供的引用内容,特别是引用[1]中提到的将YOLOv5识别结果输出到MySQL数据库的方法。用户现在想了解如何用MySQL数据库存储和管理YoloV11模型的预测结果。由于YoloV11与YOLOv5在输出数据的结构上相似(通常包括检测到的物体类别、位置坐标、置信度等),我们可以采用类似的方法。步骤如下:1.设计合适的数据库表结构来存储预测结果。根据引用[1],可以设置一个表,包含图片信息、检测结果、间等字段。2.修改YoloV11的预测代码(通常是detect.py或类似的推理脚本),在检测到结果后,将结果写入数据库。我们根据引用[3]中提到的系统架构,特别是数据库设计部分,来设计表结构。假设我们需要存储的信息包括:-图片(可以存储图片的路径,或者直接将图片转为base64编码存储为longtext,但后者会占用很大空间,通常存路径)-检测间(datetime)-检测结果(可以存储为JSON格式的字符串,包含每个检测目标的类别、置信度、坐标等信息)因此,我们可以创建如下的表(在名为demo的数据库中,表名为detections):列:-id:INTAUTO_INCREMENTPRIMARYKEY,-image_path:VARCHAR(255)或者image_data:LONGTEXT(根据需求选择,通常存路径更合理)-detection_time:DATETIME-detection_results:JSON或者LONGTEXT(如果MySQL版本支持JSON类型,则用JSON,否则用TEXT存储JSON字符串)注意:用户引用[1]中设置了两列:picture(longtext)和time(datetime)。但我们建议存储图片路径而非整个图片数据,除非有特殊需求。接下来,我们在YoloV11的推理代码中,当检测完后,将结果存入数据库。步骤:1.连接数据库:在代码开头创建数据库连接。2.修改推理循环:在每一张图片推理完后,将结果整理并插入数据库。3.关闭连接:推理结束后关闭数据库连接。示例代码(修改YoloV11的detect.py):-引入必要的库:如pymysqljsondatetime-配置数据库连接参数(host,user,password,database等)-在推理循环中,对于每一张图片:*记录当前间*将检测结果(通常是一个包含多个检测框的列表)转换JSON字符串*将图片路径(或处理后的图片数据)和检测结果字符串以及间存入数据库注意:如果检测结果中包含图片本身(例如base64编码),那么image_data列可以用LONGTEXT存储。但更推荐只存图片路径,图片文件保存在服务器上。下面是一个代码修改的示例(只展示关键部分):</think> 根据您的需求,我将详细说明如何使用MySQL数据库存储和管理YOLOv11模型的预测结果,以下是完整的实现方案: ### 数据库设计与创建 首先设计合理的数据库表结构来存储检测结果: ```sql CREATE DATABASE IF NOT EXISTS object_detection; USE object_detection; CREATE TABLE IF NOT EXISTS detections ( id INT AUTO_INCREMENT PRIMARY KEY, image_path VARCHAR(255) NOT NULL, -- 检测的图片路径 detection_time DATETIME DEFAULT CURRENT_TIMESTAMP, -- 检测间 class_name VARCHAR(50) NOT NULL, -- 检测到的类别名称 confidence FLOAT NOT NULL, -- 置信度(0-1) x_min INT NOT NULL, -- 边界框坐标 y_min INT NOT NULL, x_max INT NOT NULL, y_max INT NOT NULL, full_json TEXT -- 完整检测结果的JSON备份 ); ``` ### 检测结果封装方案 在Python中创建数据封装类: ```python import json from datetime import datetime class DetectionResult: def __init__(self, img_path, class_name, conf, bbox): self.image_path = img_path self.class_name = class_name self.confidence = conf self.bbox = bbox # [x_min, y_min, x_max, y_max] self.timestamp = datetime.now() def to_sql_dict(self): return { 'image_path': self.image_path, 'detection_time': self.timestamp, 'class_name': self.class_name, 'confidence': self.confidence, 'x_min': self.bbox[0], 'y_min': self.bbox[1], 'x_max': self.bbox[2], 'y_max': self.bbox[3], 'full_json': json.dumps({ 'class': self.class_name, 'confidence': self.confidence, 'bbox': self.bbox }) } ``` ### MySQL数据库操作类 ```python import mysql.connector from mysql.connector import Error class DetectionDB: def __init__(self, host, user, password, database='object_detection'): self.connection = mysql.connector.connect( host=host, user=user, password=password, database=database ) self.cursor = self.connection.cursor() def insert_detection(self, detection): sql = """ INSERT INTO detections (image_path, detection_time, class_name, confidence, x_min, y_min, x_max, y_max, full_json) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) """ values = ( detection.image_path, detection.timestamp, detection.class_name, detection.confidence, *detection.bbox, detection.to_sql_dict()['full_json'] ) self.cursor.execute(sql, values) self.connection.commit() def __del__(self): if self.connection.is_connected(): self.cursor.close() self.connection.close() ``` ### YOLOv11检测结果集示例 在检测脚本中添加数据库存储功能: ```python import torch from yolov11.detect import run_detection # 初始化数据库连接 db = DetectionDB('localhost', 'user', 'password') # 修改检测函数 def detect_and_store(image_path): # YOLOv11检测(伪代码) results = run_detection(weights='yolov11.pt', source=image_path) # 处理每个检测结果 for det in results.xyxy[0]: # 假设结果格式为[x_min, y_min, x_max, y_max, conf, class] class_id = int(det[5]) class_name = results.names[class_id] # 封装检测结果 detection = DetectionResult( img_path=image_path, class_name=class_name, conf=float(det[4]), bbox=[int(x) for x in det[:4]] ) # 存入数据库 db.insert_detection(detection) ``` ### 查询与管理示例 ```sql -- 查询所有西红柿检测结果 SELECT * FROM detections WHERE class_name = 'tomato'; -- 统计各物体检测次数 SELECT class_name, COUNT(*) AS detection_count FROM detections GROUP BY class_name ORDER BY detection_count DESC; -- 删除低置信度记录 DELETE FROM detections WHERE confidence < 0.5; ``` ### 数据库优化建议 1. **索引优化**:在常用查询字段(如`class_name`, `detection_time`)创建索引 ```sql CREATE INDEX idx_class ON detections(class_name); CREATE INDEX idx_time ON detections(detection_time); ``` 2. **分区管理**:按间范围分区处理历史数据 ```sql ALTER TABLE detections PARTITION BY RANGE (YEAR(detection_time)) ( PARTITION p2023 VALUES LESS THAN (2024), PARTITION p2024 VALUES LESS THAN (2025) ); ``` 3. **定归档**:定期将历史数据迁移至归档表 以上方案通过封装检测结果、结构化存储和高效查询,实现了YOLOv11预测结果的完整数据库管理流程[^1][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值