How to set values to jtable? - java

I have two tables in my database(using mysql workbench), but I can't set the data in that tables at the same time to jtable. How can I fix this issue ?
(Get the values from two tables or related fields and set those into jtable)

I mean two resultsets?
Why do you have two ReultSets? You have two options:
Change your SQL query to get the data into a single ResultSet
Don't use DBUtils to create the TableModel
In this case you need to load the data from the ResultSet manually one row at a time.
For the first ResultSet you need to create the columns for the table and then add rows of data. The basic logic would be:
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
// Read data from a table
String sql = "Select * from ???";
Statement stmt = connection.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<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
connection.close();
}
catch(Exception e)
{
System.out.println( e );
}
For the second ResultSet you just add the data to the Vector.
Then you create the DefaultTableModel using the two Vectors and you create the JTable using the TableModel.

Related

How do I show changes in my SQL table when I combined the values using GROUP BY?

I have this database table named Store_Data and I show three columns in the JTable.
Here are the columns:
NUMBERS
AMOUNT
DATE
How do I show the other columns in the jtable? The other columns are missing
I managed to obtain combined values using this SQL command, "SELECT NUMBERS, SUM(AMOUNT) FROM Store_Data GROUP BY NUMBERS", and I managed show it in the JTable.
However, In the JTable I only see the column NUMBERS and another column showing all the sum of the AMOUNT values. I don't see the other columns in the Jtable.
Here is my code,
private JTable showRecords(Connection con)
{
try
{
column.clear();
data.clear();
_stmt = con.createStatement();
//String getColumn = "SELECT * FROM APP.NYPMTRIPLESTRAIGHT";
/*this is only a test*/
String test = "SELECT NUMBERS, SUM(AMOUNT) FROM Store_Data GROUP BY NUMBERS";
ResultSet rs = _stmt.executeQuery(test);
//this will collect the data from the database
ResultSetMetaData metaData = rs.getMetaData();
//this will count all the columns from
int column_count = metaData.getColumnCount();
for(int j = 1; j <= column_count; j++)
{
column.add(metaData.getColumnName(j));
}
while(rs.next())
{
Vector<Object> vector = new Vector<Object>();
for(int i = 1; i <= column_count; i++)
{
vector.add(rs.getObject(i));
}
data.add(vector);
}
_records = new JTable(data, column);
return _records;
} catch (SQLException ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return _records;
}
NOTE: I know it is wrong to use Vector. I am only using it for testing.
Your query sums all the values of AMOUNT and displays the sum using a Group by clause.
Group by will group similar values into one entity based on the functions used. ["sum" in your case].
You need to get the numbers and amount from your database simply
SELECT NUMBERS, AMOUNT FROM APP.NYPMTRIPLESTRAIGHT;
then display the resultset data in your JTable.
Try this:
SELECT
t1.NUMBERS,
CONCAT(YEAR(T1.DATE) , '-' , MONTH(t1.DATE) , '-' ,DAY(t1.DATE)) as DATE,
SUM(AMOUNT) AS AMOUNT
FROM table1 t1
GROUP BY 1, 2
And here you have the sqlfiddle

add column to jtable dynamically on netbeans

my code is this :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model=(DefaultTableModel)pl.getModel();
String urlBaseDonnes="jdbc:mysql://localhost:3306/test";
Connection con;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException ex){
System.out.println(ex);
}
try{
con =DriverManager.getConnection(urlBaseDonnes,"root","");
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM news");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
int j=0;
pl.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"ddd","fgg","nl"}));
// get the name of the column, and changing it
for (int i = 1 ; i <= numberOfColumns; i++) {
ChangeName(pl,j,rsMetaData.getColumnName(i));
System.out.println(rsMetaData.getColumnName(i));
System.out.println(j);
j= j+1;
}
String query="SELECT * FROM news";
rs=stmt.executeQuery(query);
//Show the database
while(rs.next()){
String id=rs.getString("id");
String titre=rs.getString("titre");
String contenu=rs.getString("contenu");
model.addRow(new Object[]{id,titre,contenu});
}
rs.close();
}
con.close();
System.out.println("close the database");
}catch(SQLException ex){
System.out.println(ex);
}
}
My goal is to change the name of the columns dynamically when i change the name of my table, this code can change the name of the column but when it's come to showing the content of the database it doesn't work, also i can't add column, for exemple if i choose a table that have 4 column, i'll have an error. I tried to add column using a DefaultTableModel but it didn't work.
could you please help me with the part of adding column dynamically ? and tell me why this code doesn't show what's on the database ?
Thanks
that the data that are in my database are not shown. this code only changes the name of the column.
First you access the TableModel of the table:
DefaultTableModel model=(DefaultTableModel)pl.getModel();
Then you change the TableModel of the table:
pl.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"ddd","fgg","nl"}));
Then you add the data from the database to the "old" model:
model.addRow(new Object[]{id,titre,contenu});
So the data is NOT added to the current model.
If you want to create a new model then your code should be something like:
DefaultTableModel model = DefaultTableModel(Object[] columnNames, int rowCount);
pl.setModel( model );
Then your code will add the database data to the real model.
The question is why are you trying to hardcode the column name? When you do a select * from the database you don't know how many columns of data will be returned. You should be using more generic code. See the TableFromDatabaseExample.java code from Table From Database.

Modifying column headers of JTable with MySQL data

I have a JTable that retrieves information from a MySQL database table. The column headers are named just like how they are in the database.
Here is the code to create the JTable:
JScrollPane spBlockViewSchedule = new JScrollPane();
spBlockViewSchedule.setBounds(10, 285, 763, 185);
pnlBlockSched.add(spBlockViewSchedule);
tblBlockViewSchedule = new JTable();
spBlockViewSchedule.setViewportView(tblBlockViewSchedule);
Here is the code that populates the JTable:
private void populateTable(String sql, JTable table) {
try {
pst = DbConnection.conn.prepareStatement(sql);
rs = pst.executeQuery();
} catch(Exception ex) {
ex.printStackTrace();
}
table.setModel(DbUtils.resultSetToTableModel(rs));
}
How do I change the column names displayed in the JTable without changing the column names of the database table itself?
Create an empty DefaultTableModel with code like:
String[] columnNames = {"Course Code", "Subject Code", "Year Level", ...};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
Then in the code where you read the data from the ResultSet you add the data to the TableMOdel using the addRow(....) method. Something like:
while (rs.next())
{
Vector row = new Vector();
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
model.addRow( row );
}
Finaly you create the table using:
JTable table = new JTable( model );
Edit:
Since you are using 3rd party code you either need to change the way you add data to the model. I gave you basic code above. You can see the Table From Database Example source code from Table From Database for a complete example.
Or, you can modify the column headers after the table is created with code like:
table.getColumn("course_code").setHeaderValue("Course Code");
...
table.repaint();
Edit 2:
You can get the TableColumn from the TableColumnModel:
TableColumnModel tcm = table.getTableColumnModel();
tcm.getColumn(0).setHeaderValue("Course Code");
...
table.repaint();
I am currently facing the same problem as you did.
This line:
table.setModel(DbUtils.resultSetToTableModel(rs));
provided by r2xml.jar is pretty handy :)
I overcame the problem by setting alias to my sql SELECT statement.
For example,
SELECT
EngagementMethodID AS [ID],
EngagementMethodDescription AS [Engagement Method Description]
FROM [STUDENT].[EngagementMethod]
This will populate the column header as ID and Engagement Method Description as wanted.
Hope it helps.. Despite the age of this question? haha... Just sharing
try this
int colCount = 0;
ResultSetMetaData rsMetaData = null;
colCount = rsMetaData.getColumnCount();
for (int k = 1; k <= colCount; k++) {
{ String columnName = null;
columnName = rsMetaData.getColumnName(k);
System.out.println(columnName);
}
use this code simultaneously with your fetching code.
Each JTable has a TableModel. This TableModel defines the columns(Names and data types)
so find your table model and change it accordingly.

extra column automatically appended in jtable (how to remove it )

I am working on a java project
I am using jdk 1.6
I am want to add data from database in jtable
I have achieved this by using DefaulTableModel
and I got the column names by using ResultSetMetadata
but the problem is
**I am getting a extra column name A at the 0th index of jtable
I want to remove this column
it looks like this
A | deptno
I only need deptno
**
the code used for creating this model is
private void updateTable() throws Exception {
String sqlrow = "Select count(*) from emp";
rs= db.sta.executeQuery(sqlrow);
rs.next();
int rows=rs.getInt(1);
System.out.println(""+rows);
String sqldata = "SELECT deptno FROM emp";
rs =db.sta.executeQuery(sqldata);
rsMD = rs.getMetaData();
numberOfColumns = rsMD.getColumnCount();
ColumnNames = new String[numberOfColumns+1];
System.out.println(""+numberOfColumns);
for(int i=1;i<=numberOfColumns;i++)
{
String colName=rsMD.getColumnName(i);
ColumnNames[i] = colName;
System.out.println(""+ColumnNames[i]);
}
//Cj is a method which takes sqlQuery , rows, column
Object[][] rowData=CJ(sqldata,rows,numberOfColumns);
//jt is table name
jt.setModel(new DefaultTableModel(rowData,ColumnNames));
}
// code for cj()
public Object[][] CJ(String sql,int rows,int cols)
{
Object[][] obj=new Object[rows][cols+1];
ResultSet rs=null;
try{
rs= db.sta.executeQuery(sql);
int c=0;
while(rs.next())
{
for(int i=1;i<=cols;i++)
{
obj[c][i]=rs.getString(i);
}
c++;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return obj;
}
I am using this code on
button click
updateTable();
jsp = new JScrollPane(jt); // jt is Jtable
jp.add(jsp); //jp is jpanel
please help me out
Not following the naming convention makes it hard to read, but I would suggest to take a closer look at the following piece of code
numberOfColumns = rsMD.getColumnCount();
ColumnNames = new String[numberOfColumns+1];
System.out.println(""+numberOfColumns);
for(int i=1;i<=numberOfColumns;i++)
{
String colName=rsMD.getColumnName(i);
ColumnNames[i] = colName;
System.out.println(""+ColumnNames[i]);
}
Here you explicitly use more column names then numberOfColumns. Idem for your CJ method, where you start at index 1.
Just start all those for loops at index 0, make the arrays one shorter and everything should work

JTable doesn't show the newly inserted row/data

I have a JTable and I populte the table as follows:
jTable_Std_info.setModel(DBControler.getALLStudents());
And the following is a static method in a class named DBControler which retrieves all the data from the database(Oracle).
public static DefaultTableModel getALLStudents() throws SQLException, Exception {
DefaultTableModel tableModel = new DefaultTableModel();
Vector rows = new Vector();
Vector columns = new Vector();
try {
conn = geConnection();
cst = conn.prepareCall("{? = call std_getInfoFunc}");
cst.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
cst.execute();
res = (ResultSet) cst.getObject(1);
System.out.print(res);
ResultSetMetaData rsm = res.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
columns.addElement(rsm.getColumnName(i));
}
int row = 0;
while (res.next()) {
Vector vRow = new Vector(); //to store the current row
//System.out.println("Row " +row+"\n");
for (int i = 1; i <= rsm.getColumnCount(); i++) {
String columnValue = res.getString(i);
vRow.addElement(columnValue);
}
row += 1;
rows.addElement(vRow);
}
tableModel.setDataVector(rows, columns);
} catch (SQLException e) {
e.printStackTrace();
} finally {
res.close();
conn.close();
}
return tableModel;
}
So far everything works fine, but the problem is that if I insert a new record in the database, the JTable doesn't get the newly inserted row/data. Why is that and how can I fix this problem?
UPDATE:
It's retrieving the data when I commit my new insertion. So do I have to commit each time I update? Or is there any other ways to do this?
I think that you looking for Oracle Built-In Database Change Notification, not sure if is accesible for Oracle's in free-versions, if not then never mind, for MySQL is there two or three similair API for Java JDBC
But the problem is that if I insert a new record in the database, the JTable doesn't get the newly inserted row/data. Why is that?
The TableModel doesn't know when the database is updated.
and how can I fix this problem?
If your application is adding the row to the database then it also needs to add a row to the TableModel at the same time.

Categories

Resources