我开发了一个小应用程序,必须使用3D条形图显示公司的前十大销售项目。这些项目将从mysql数据库中检索。
我知道如何从mysql数据库中检索数据,但是如何让它与Neteans上的条形图一起使用?
我如何才能实现这一目标或哪里是帮助我实现这一目标的最佳资源?
答案 0 :(得分:1)
实现此目的的方法首先是使用以下编码建立数据库连接,如下所示:
//connects to the database
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/DBName","root","password");
//select statement calling data from the sales database
PreparedStatement stmt = con.prepareStatement("SELECT * FROM dbsales ORDER BY usold DESC LIMIT 10");
ResultSet rs = stmt.executeQuery();
那么你需要使用以下编码来创建和显示netbeans中的图表
//creates the graph object
DefaultCategoryDataset ddataset = new DefaultCategoryDataset();
while (rs.next())
{
//retrieves data from the database for the graph
ddataset.setValue(new Double(rs.getDouble("usold")), rs.getString("pbrand") + " " + rs.getString("pname"), rs.getString("pid"));
}
//generates the graph
JFreeChart chart = ChartFactory.createBarChart3D("Top 10 Selling Products", "Products", "Number of Units Sold", ddataset);
//creates the graph title
chart.getTitle().setPaint(Color.RED);
//plots the graph
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLUE);
//creates the frame
ChartFrame frame2 = new ChartFrame("Top 10 Selling Products", chart);
//sets the frame visible
frame2.setVisible(true);
//sets the frame size
frame2.setSize(900,700);
你需要把它放在try catch块中。
请记住,您需要一个Jar文件,允许您从图表的JAR文件中导入必要的数据。
以下是完整的编码集:
//method for top ten graph
private void topten()
{
try
{
//connects to the database
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/DBName","root","password");
//select statement calling data from the sales database
PreparedStatement stmt = con.prepareStatement("SELECT * FROM dbsales ORDER BY usold DESC LIMIT 10");
ResultSet rs = stmt.executeQuery();
//creates the graph object
DefaultCategoryDataset ddataset = new DefaultCategoryDataset();
while (rs.next())
{
//retrieves data from the database for the graph
ddataset.setValue(new Double(rs.getDouble("usold")), rs.getString("pbrand") + " " + rs.getString("pname"), rs.getString("pid"));
}
//generates the graph
JFreeChart chart = ChartFactory.createBarChart3D("Top 10 Selling Products", "Products", "Number of Units Sold", ddataset);
//creates the graph title
chart.getTitle().setPaint(Color.RED);
//plots the graph
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.BLUE);
//creates the frame
ChartFrame frame2 = new ChartFrame("Top 10 Selling Products", chart);
//sets the frame visible
frame2.setVisible(true);
//sets the frame size
frame2.setSize(900,700);
}
catch(Exception e)
{
//error message for when the graph cannot be generated
JOptionPane.showMessageDialog(null, "Error 111: Unable to identify and load best ten sellers for graph", "Database Error", JOptionPane.ERROR_MESSAGE);
}
}