adding rows with data from a Mysql table to jtable - java

Adding the colums works, but i am stuck when i want to add the data of the columns stored in a mysql database to the jtable. it ask for a object vector[][] but i have no clue what to give
Connection con;
DefaultTableModel model = new DefaultTableModel();
public Hoofdscherm() {
initComponents();
uitvoerSpelers.setModel(model);
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/fullhouse", "root", "hamchi50985");
// selecteer gegevens uit fullhouse.speler tabel
PreparedStatement stat = con.prepareStatement("SELECT * FROM fullhouse.speler");
// sla deze GEGEVENS op in een resultset
ResultSet resultaat = stat.executeQuery();
// haal alle kolomnamen op PUUR VOOR DE MODEL VAN JTABLE
ResultSetMetaData data = resultaat.getMetaData();
String[] colum = new String[15];
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
while (resultaat.next()) {
Object[] gegevens = new String[] {resultaat.getString(1)};
model.addRow(gegevens[0]);
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}

I think you need something like this.
Note
1. Also add your columns separate to resultset data. Like I showed in my code below.
Vector<String> rowOne = new Vector<String>();
rowOne.addElement("R1C1");
rowOne.addElement("R1C2");
Vector<String> rowTwo = new Vector<String>();
rowTwo.addElement("R2C1");
rowTwo.addElement("R2C2");
Vector<String> cols = new Vector<String>();
Vector<Vector> vecRow = new Vector<Vector>();
vecRow.addElement(rowOne);
vecRow.addElement(rowTwo);
cols.addElement("Col1");
cols.addElement("Col2");
JTable table = new JTable(vecRow, cols);
Edit
For you convenience and requirement You can follow code structure below.
Vector<String> rows = new Vector<String>();
Vector<Vector> dBdata = new Vector<Vector>();
// Add Columns to table
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
}
while (resultaat.next()) {
// add column data to rows vector
// Make sure that all data type is in string because of generics
rows.add(resultaat.getString("columnName1"));
rows.add(resultaat.getString("columnName2"));
rows.add(resultaat.getString("columnName3"));
// add whole row vector to dBdata vector
dBdata.addElement(rows);
}
model.addRow(dBdata);
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Class Vector Javadoc
I hope this will help you.

The line model.addRow(gegevens[0]);is incorrect.
You should do something like this:
String[] colum = new String[15];
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
while (resultaat.next()) {
Object[] gegevens = new String[] {resultaat.getString(1)};
model.addRow(gegevens);
}
}
Also you need to check DefaultTableModel
According to the documentation of DefaultTableModel:
This is an implementation of TableModel that uses a Vector of Vectors
to store the cell value objects.

Related

Binary file proplem with jTableModel

i am writing in binary file objects by gui and when i list them in table only one line appears like this
not all data appers
and here is the code to list
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Object rowData[] = new Object[5];
model.setRowCount(0);
Apparels a = new Apparels();
ArrayList<Apparels> app = new ArrayList<Apparels>();
app = a.listApparels();
for (Apparels x : app) {
rowData[0] = x.getStockid();
rowData[1] = x.getPricePerItem();
rowData[2] = x.getQuantity();
rowData[3] = x.getType();
rowData[4] = x.getCateogryname();
model.addRow(rowData);
}
You're re-using rowData to fill the properties, which means that for each row, it will have the same data
Maybe try using something more like...
for (Apparels x : app) {
Object rowData[] = new Object[5];
rowData[0] = x.getStockid();
rowData[1] = x.getPricePerItem();
rowData[2] = x.getQuantity();
rowData[3] = x.getType();
rowData[4] = x.getCateogryname();
model.addRow(rowData);
}
The primary issue is, the reference to rowData never changes, but the content in each element does, so once you've finished looping the, model will have a list of references all pointing to the same instance of rowData

How To Populate Jtable Using rs2xml jar library

Dear friends i would like to know how to display the result set to jtable using rs2xml i know jtablename.setmodel(dbutils.setresultsettotable(rs)); but i would like to know that how to retriev all records and show them in jtablle my code is
private void search_by_topic() throws SQLException, ClassNotFoundException {
try
{
SessionFactory sf;
Configuration cfg=new Configuration();
System.out.println("search_by_topic me agaya");
cfg.configure("hiber_config/hibernate.cfg.xml");
sf=cfg.buildSessionFactory();
Session ses=sf.openSession();
ses.beginTransaction();
Query qr1=ses.createQuery("from Topic where chapter_id=:chapter_id");
qr1.setParameter("chapter_id", chap_id);
List<Topic> topic_list=qr1.list();
top_id=topic_list.get(jComboBox3.getSelectedIndex()).getTopic_id();
System.out.println("Topic ID is "+top_id);
Query qr2=ses.createQuery("from Test as t where t.import_level=:import_level and t.import_level_id=:import_level_id");
qr2.setParameter("import_level", topicimport);
qr2.setInteger("import_level_id",top_id);
List<Test> test_list=qr2.list();
//Field[] fields = null;
System.out.println("Size of test_list is"+test_list.size());
//Iterator<Test> itr=test_list.iterator();
int[] test_id=new int[test_list.size()];
for(int j=0;j<test_list.size();j++)
{
System.out.println("Test_List Import Wale me agaya");
//fields=t.getClass().getDeclaredFields();
test_id[j]=test_list.get(j).getId();
System.out.println("test_id: is "+test_id[j]);
}
System.out.println("Size of test_id array is "+test_id.length);
for(int j=0;j<test_id.length;j++)
{
System.out.println("test_id now is "+j);
int studentid=98;
String sqlquery="SELECT ST.ID id,ST.STUDENT_ID student_id,ST.attemptNumber attempt_Number,ST.TEST_ID testId,ST.TEST_ID student_test_id,T.description description,T.test_duration test_duration,T.test_score Test_Score,ST.SCHEDULED_START_TIME_BEGIN scheduled_start_time_begin,ST.SCHEDULED_START_TIME_END scheduled_start_time_end,ST.TEST_START_DATE test_start_date,ST.LAST_ACTIVE_TIME test_last_active_time,ST.TEST_ATTEMPTED test_attempted,ST.ALLOW_VIEW_REPORT allow_view_report FROM student_test as ST,test as T WHERE ST.PAYMENT_STATUS='A' AND ST.TEST_ID = T.id AND ST.STUDENT_ID='"+studentid+"' AND ST.TEST_ATTEMPTED='0' AND T.id='"+test_id[j]+"' ORDER BY ST.ID";
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school_db","root","");
Statement pst=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=pst.executeQuery(sqlquery);
System.out.println(rs.getRow());
System.out.println(rs.toString());
jTable1.revalidate();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
//jTable1.revalidate();
/*SessionFactory sf1;
Configuration cfg1=new Configuration();
System.out.println("join query me agaya");
cfg1.configure("hiber_config/hibernate.cfg.xml");
sf1=cfg.buildSessionFactory();
Session ses1=sf1.openSession();
ses1.beginTransaction();
ses1.doWork(new Work()
{
#Override
public void execute(java.sql.Connection cnctn) throws SQLException
{
java.sql.PreparedStatement pst=cnctn.prepareStatement(sqlquery);
rs=pst.executeQuery();
System.out.println(rs.toString());
}
});
ses1.getTransaction().commit();
}
ses.getTransaction().commit();
System.out.println("Test Data Retrieved");
ses.close();*/
}
}
catch(HibernateException e)
{
e.printStackTrace();
}
}
}
my code is working here correctly and i am able to retrieve all the resultset but in jtable i am only getting the last loop record not every loop record
Please help me
private void search_by_topic() throws SQLException, ClassNotFoundException {
try
{
SessionFactory sf;
Configuration cfg=new Configuration();
System.out.println("search_by_topic me agaya");
cfg.configure("hiber_config/hibernate.cfg.xml");
sf=cfg.buildSessionFactory();
Session ses=sf.openSession();
ses.beginTransaction();
Query qr1=ses.createQuery("from Topic where chapter_id=:chapter_id");
qr1.setParameter("chapter_id", chap_id);
List<Topic> topic_list=qr1.list();
top_id=topic_list.get(jComboBox3.getSelectedIndex()).getTopic_id();
System.out.println("Topic ID is "+top_id);
Query qr2=ses.createQuery("from Test as t where t.import_level=:import_level and t.import_level_id=:import_level_id");
qr2.setParameter("import_level", topicimport);
qr2.setInteger("import_level_id",top_id);
List<Test> test_list=qr2.list();
//Field[] fields = null;
System.out.println("Size of test_list is"+test_list.size());
//Iterator<Test> itr=test_list.iterator();
int[] test_id=new int[test_list.size()];
for(int j=0;j<test_list.size();j++)
{
System.out.println("Test_List Import Wale me agaya");
//fields=t.getClass().getDeclaredFields();
test_id[j]=test_list.get(j).getId();
System.out.println("test_id: is "+test_id[j]);
}
System.out.println("Size of test_id array is "+test_id.length);
for(int j=0;j<test_id.length;j++)
{
System.out.println("test_id now is "+j);
int studentid=98;
String sqlquery="SELECT ST.ID id,ST.STUDENT_ID student_id,ST.attemptNumber attempt_Number,ST.TEST_ID testId,ST.TEST_ID student_test_id,T.description description,T.test_duration test_duration,T.test_score Test_Score,ST.SCHEDULED_START_TIME_BEGIN scheduled_start_time_begin,ST.SCHEDULED_START_TIME_END scheduled_start_time_end,ST.TEST_START_DATE test_start_date,ST.LAST_ACTIVE_TIME test_last_active_time,ST.TEST_ATTEMPTED test_attempted,ST.ALLOW_VIEW_REPORT allow_view_report FROM student_test as ST,test as T WHERE ST.PAYMENT_STATUS='A' AND ST.TEST_ID = T.id AND ST.STUDENT_ID='"+studentid+"' AND ST.TEST_ATTEMPTED='0' AND T.id='"+test_id[j]+"' ORDER BY ST.ID";
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school_db","root","");
Statement pst=con.createStatement();
rs=pst.executeQuery(sqlquery);
while(rs.next())
{
//JOptionPane.showMessageDialog(null, "Table me Agaaya");
System.out.println("Number of rows:- "+rs.getRow());
System.out.println(rs.toString());
}
}
ses.getTransaction().commit();
System.out.println("Test Data Retrieved");
ses.close();
}
catch(HibernateException e)
{
e.printStackTrace();
}
}
}
this is my code and its working fine in system.out.println it showing all data now can u tell me how to pass this data in jtable and to let you know when i use dbutils its also retrieve column name automatically and i am not giving the column name in jtable manually
i know jtablename.setmodel(dbutils.setresultsettotable(rs));
Well DBUtils creates a single TableModel
but in jtable i am only getting the last loop record not every loop record
You keep replacing the old TableModel with a new TableModel.
So you have two choices:
You need to create multiple tables, one for each TableModel and add each JTable to the frame
You need to copy the data from each TableModel into a master TableModel and then display the master TableModel into in single JTable. So this means that outside of the loop your create a DefaultTableModel with just the column names and 0 rows of data. Then instead each loop your then copy each row of data from the DBUtils model to your main TableModel. Then outside the loop your create the table using the main TableModel.
Edit:
The basic structure of the code would be something like:
// Create an empty table model
String[] columnNames = {"Column1", "Column2", ...};
DefaultTableModel groupModel = new DefaultTableModel(columnNames,0);
...
// loop for all the ids
for(int j=0;j<test_id.length;j++)
{
...
// copy the data from the idc table model to the group table model
DefaultTableModel idModel = DbUtils.resultSetToTableModel(rs);
for (int i = 0; I < idModel.getRowCount())
{
Vector<Object> row = new Vector<Object>();
for (int j = 0; j < rsModel.getColumnCount()
row.addElement( rsModel.getValueAt(i, j);
groupModel.addRow( row );
}
}
JTable table = new JTable( groupModel );

display database table in java

I am trying to get a table to populate from my database. I followed a tutorial and my code is displayed below, however I am getting this error and cannot figure out why. In my database I have 'first name, last name, address, city, state, zip' not sure if this info is needed to help me with my question
Could someone please help
thank you in advanced for your help.
package medicalrecords;
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
public class TableFromDatabase extends JPanel {
private Connection conexao = null;
public TableFromDatabase() {
Vector columnNames = new Vector();
Vector data = new Vector();
try {
// Connect to an Access Database
conexao = DriverManager.getConnection("jdbc:derby://" + "localhost"
+ ":1527/Medical Records", "root", "password");
// Read data from a table
String sql = "select * from SD2799.PATIENTRECORDS";
try (Statement stmt = conexao.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i));
}
// Get row data
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
}
conexao.close();
} catch (Exception e) {
System.out.println(e);
}
// Create table with database data
JTable table = new JTable(data, columnNames) {
#Override
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
JPanel buttonPanel = new JPanel();
add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Patient Records");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableFromDatabase newContentPane = new TableFromDatabase();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
});
}
}
Your message "uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details" is not an error, but it is a warning. The Vector class is generic (Generics were added to Java in 1.5), which means that it takes a type parameter. Here, it means the type of objects it can hold.
If you were to re-compile with the command line option "-Xlint:unchecked" as the warning suggests, the compiler will give you more details about the warning, including the offending lines.
You didn't supply a type parameter for any of your Vectors, so they are raw, meaning no type parameter was supplied. The compiler is warning you that you are using raw types, and that your type safety is at risk.
You can supply the appropriate type parameters to eliminate the warnings. In the TableFromDatabase constructor, towards the top:
Vector<String> columnNames = new Vector<String>();
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
and later on in the same constructor:
Vector<Object> row = new Vector<Object>(columns);
However, Vector was superseded by ArrayList (and its List interface) in Java 1.2. In fact Vector was retrofitted then to implement the new-then List interface. It doesn't look like you need Vector's thread safety, so it's recommended to use ArrayList instead.
List<String> columnNames = new ArrayList<String>();
List<Vector<Object>> data = new ArrayList<List<Object>>();
and
List<Object> row = new ArrayList<Object>(columns);
As of Java 1.7, you can use the "diamond operator", and remove the type parameter on the right side of the assignment operator, letting Java infer the proper type, e.g.:
List<String> columnNames = new ArrayList<>();
List<Vector<Object>> data = new ArrayList<>();
and
List<Object> row = new ArrayList<>(columns);

getting values from Database to JLabel

i have a table in the database of 4rows and 4columns. each column holds a different data.
now i want to retrieve all the data in the database and put them on JLabel on another form. i.e
in my Database i have.
packageName.....monthlyFee..... YearlyFee....... TotalFee
Regular......................150..................300....................450
Gold.........................300...................400..................700
..... ..... .... ....
now i have a form that i have put 4 empty JLabels in four rows but how do i retrieve the values from the database and place each value in the appropriate Label?.
This is what i've done but i still cant get around it. im stuck.
Thank you anyone.
public void getPrices()
{
String srt ="SELECT * FROM program_tbl";
try
{
con.connect();
ps = con.con.prepareStatement(srt);
rs = ps.executeQuery();
ResultSetMetaData data = rs.getMetaData();
int colums = data.getColumnCount();
while(rs.next())
{
Vector rows = new Vector();
for (int i = 1; i < colums; i++)
{
rows.addElement(rs.getObject(i));
}
.....................................................................
If you want to get this data as a string then you could probably try something like:
Vector<String> rows = new Vector<String>();
while(rs.next()) {
String rowEntry = rs.getString("packageName") +
rs.getString("monthlyFee") +
rs.getString("yearlyFee") +
rs.getString("totalFee") +
rows.add(rowEntry);
}
If not String, but an object to use later, then you can create a class:
public class MyObject {
private String packageName;
private int monthlyFee;
private int yearlyFee;
private int totalFee;
public MyObject (String name, int monthlyFee, int yearlyFee, int totalFee) {
this.packageName = name;
this.monthlyFee = monthlyFee;
this.yearlyFee = yearlyFee;
this.totalFee = totalFee;
}
/*Setters
*And
*Getters*/
}
And then use it as:
Vector<MyObject> rows = new Vector<MyObject>();
while (rs.next()) {
MyObject obj = new MyObject(rs.getString("packageName")
, rs.getInt("montlyFee")
, rs.getInt("yearlyFee")
, rs.getInt("totalFee")
);
rows.add(obj)
}
So say we now have a vector with String values - Vector<String> rows;
now i would like to create those JLabels.
JLabel[] myLabels = new JLabel[v.size()];
for(int i=0; i<rows.size(); i++) {
as[i] = new JLabel(rows.get(i));
}
And now we have an array of JLabels ready to be put to applet.
Don't use a JLabel. There is no way you can easily format the data so that you get tabular data.
Instead you should be using a JTable. Read the section from the Swing tutorial on How to Use Tables for more information. You can also search the forum for examples of using a JTable with a ResultSet.

JTable Swing retrieve data

I'm trying to populate a table with data from a database however i am having some issues with it. Could someone provide me with an example? (so the table takes in an Object[][] parameter for the data). I have the following basic code to display a table ;
class table extends JFrame
{
JTable table;
public table()
{
setLayout(new FlowLayout());
String[] columnNames = {"test","test","test"};
Object[][] data= {{"test","test","test"},{"test","test","test"}};
table = new JTable(data,columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500,100));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
Two years ago, during my time in technical school, I wrote a little library help solve some of the problems proposed by the exercises, which included a a DatabaseTableModel.
The class extends from AbstractTableModel, which means you can set it as the your JTable's data source.
Here's the algorithm that constructs a model from a ResultSet:
public final void constructModel(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
rs.last();
rowCount = rs.getRow();
int columnCount = rsmd.getColumnCount();
// DatabaseColumn simply holds a name and a Class<?>.
columns = new DatabaseColumn[columnCount];
// This is the Object[][] array that you were talking about.
// It holds all the data from the ResultSet.
data = new Object[columnCount][rowCount];
for (int i = 0; i < columnCount; ++i) {
// Figure out the column name and type.
int j = i + 1;
String colName = rsmd.getColumnLabel(j);
Class<?> colClass = String.class;
try {
colClass = Class.forName(rsmd.getColumnClassName(j));
} catch (ClassNotFoundException ex) {
colClass = String.class;
}
columns[i] = new DatabaseColumn(colName, colClass);
// Get the data in the current column as an Object.
rs.beforeFirst();
for (int k = 0; rs.next(); ++k) {
data[i][k] = rs.getObject(j);
}
}
// Notify listeners about the changes so they can update themselves.
fireTableStructureChanged();
}
The class worked when I used it in school, but it isn't exactly production code. When I look at it today, I start to see problems.
One problem is that it is loading the entire contents of the ResultSet into memory. Could get ugly pretty quickly.
Also, the algorithm isn't exactly optimal. It loops around with the database cursor as if it was nothing; I suppose that it would be less costly for the database if it had retrieved all the objects in the current row first and assigned them to their appropriate columns before moving on to the next row.
Nevertheless, I think it is a good enough starting point.

Categories