"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Populate a JFreechart TimeSeriesCollection with Time Series Data from a MySQL Database?

How to Populate a JFreechart TimeSeriesCollection with Time Series Data from a MySQL Database?

Published on 2024-11-08
Browse:626

How to Populate a JFreechart TimeSeriesCollection with Time Series Data from a MySQL Database?

Populating JFreechart TimeSeriesCollection from MySQL DB

This question aims to display the temperature variation over days in a month using a JFreechart TimeSeriesCollection. However, the original implementation faced challenges with reading data accurately from the database.

Accurate Data Reading for Time Series Data

To resolve the data reading issue, it's important to consider precision in the conversion between String and Date. In the provided example, strings are directly converted to Hour.

JDBCXYDataset

To handle time series data efficiently, the JDBCXYDataset should be utilized. This dataset is designed specifically for querying and displaying time series data. Implementing JDBCXYDataset ensures that:

  • Date values are recognized and displayed correctly.
  • Data is retrieved from the database in a format compatible with time series charts.
  • The correct time format is used (Date and Timestamp in Java).

Example Implementation

Consider the following code snippet that leverages JDBCXYDataset to resolve the issue:

Connection conn = DriverManager.getConnection(...);
JDBCXYDataset jds = new JDBCXYDataset(conn);
jds.executeQuery("SELECT `data_registo`, `hora_registo`, `temperatura` FROM `registos` WHERE `idSensor` = 'BrgTH001'");

This query retrieves data from the registos table, where data_registro and hora_registro are concatenated to form the timestamp and temperatura is the value. The jds object can then be used to create a time series chart using JFreechart's createTimeSeriesChart method.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3