java—从数据库检索以显示为折线图

smtd7mpg  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(455)

我正在尝试显示数据库中的数据。我现在一次执行一个查询,以便每年得到一个特定的结果。我需要对数据库中的所有列执行此操作,但是这会使代码变得非常混乱。有没有一种更简单的方法从数据库中读取数据以显示为折线图?
当前代码段:

DefaultCategoryDataset dataset = new DefaultCategoryDataset();

String sql = "SELECT SUM(all_motor_vehicles), Year FROM Vehicle WHERE Year = 2005";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
amount = Integer.parseInt(rs.getString(1)); //get the result
yearFromDB = rs.getString(2);
System.out.println(amount + " " + yearFromDB); //print result

int amount2006;
String yearFromDB2006;
String sql2 = "SELECT SUM(all_motor_vehicles), Year FROM Vehicle WHERE Year = 2006";
pst = con.prepareStatement(sql2);
rs = pst.executeQuery();
amount2006 = Integer.parseInt(rs.getString(1)); //get the result
yearFromDB2006 = rs.getString(2);
System.out.println(amount2006 + " " + yearFromDB2006); //print result

int amount2007;
String yearFromDB2007;
String sql3 = "SELECT SUM(all_motor_vehicles), Year FROM Vehicle WHERE Year = 2007";
pst = con.prepareStatement(sql3);
rs = pst.executeQuery();
amount2007 = Integer.parseInt(rs.getString(1)); //get the result
yearFromDB2007 = rs.getString(2);
System.out.println(amount2007 + " " + yearFromDB2007); //print result

dataset.addValue(amount, allMotorVehicles, yearFromDB);
dataset.addValue(amount2006, allMotorVehicles, yearFromDB2006);
dataset.addValue(amount2007, allMotorVehicles, yearFromDB2007);

JFreeChart chart = ChartFactory.createLineChart("Traffic by Vehicle type", "Vehicle", `"Amount",dataset);`

数据库中的信息片段:

实现建议的查询时出现sql错误:
在数据库中执行查询返回:

我可以使用rs.getstring(1)检索2005年,使用rs.getstring(2)检索相应的数字,但是当我尝试通过rs.getstring(3)和rs.getstring(4)检索2006年及其数字时,我得到了一个sqlexception错误

String sql = "SELECT Year, SUM(all_motor_vehicles) AS allmotor\n" +

"FROM Vehicle\n"
            + "WHERE Year IN (2005, 2006, 2007)\n"
            + "GROUP BY YEAR;";
    pst = con.prepareStatement(sql);
    rs = pst.executeQuery();

    amount = Integer.parseInt(rs.getString(2)); //retrieves amount
    yearFromDB = rs.getString(1);
    System.out.println(amount + " " + yearFromDB); //retrieves year (2005)

    System.out.println(rs.getString(3) + " " + rs.getString(4)); //gives me an SQL ERROR
tvz2xvvm

tvz2xvvm1#

你应该做一个 GROUP BY 按年度汇总销售额的查询:

SELECT Year, SUM(all_motor_vehicles) AS all_sales
FROM Vehicle
WHERE Year IN (2005, 2006, 2007)  -- or whatever years you want in your report
GROUP BY Year;

我不想为上面的查询提供样板jdbc代码,因为您似乎已经掌握了这方面的基本知识。请注意,我为 SUM() ,以防您想使用它访问java中的结果集。

相关问题