Maruthi Sikhakolli
Maruthi Sikhakolli

Reputation: 590

Retrieving data from database and displaying in a barchart using java

I am developing a java application using net beans. It should retrieve data from database and display it in the form of a chart. Please give me suggestions how to do this in netbeans.

Upvotes: 0

Views: 3571

Answers (1)

Maruthi Sikhakolli
Maruthi Sikhakolli

Reputation: 590

I got the answer for how to retrieve data from database and display in the form of a bar chart. The below code is developed using net beans and variable name may vary depending upon the names you used.

You need to import the below packages also:

import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.jdbc.JDBCCategoryDataset;

try
      {
          String host="Database address here";
               Connection conn;
               conn = DriverManager.getConnection(host,"username","password");
         final String SQL = "SELECT column1, column2 FROM table_name";
         final CategoryDataset dataset = new JDBCCategoryDataset(conn, SQL);
         JFreeChart chart = ChartFactory.createBarChart("Report","X-Axis","Y-Axis", dataset, PlotOrientation.VERTICAL, false, false, false);
        CategoryPlot catplot = chart.getCategoryPlot();
        catplot.setRangeGridlinePaint(Color.BLACK);
        ChartPanel chartpanel = new ChartPanel(chart);
       jPanel1.removeAll();
        jPanel1.add(chartpanel, BorderLayout.CENTER);
        jPanel1.validate();    
      }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }

Upvotes: 1

Related Questions