How to display selected columns of database in a Jtable? - java

I successfully populated my JTable with the contents of my database table but I only want to show selected columns of it. Is there any way of doing this? Or is it even possible to select which column to display in a JTable?
Here is the method of populating my JTable
private void Update_table() {
try {
String sql = "select * from Members";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
Members_Table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
My database table name is "Members". "Members_Table" is the name of my JTable.

You could try changing your sql statement to only select the columns you are interested in. For instance, if Members has the columns "MemberId", "MemberFirstName", "MemberLastName" "MemberAddressFK", and you only wanted to display MemberFirstName and MemberLastName, you could change your sql to be
String sql = "select MemberFirstName, MemberLastName from Members";
You can find more details about the sql select statement at http://beginner-sql-tutorial.com/sql-select-statement.htm

If you're looking for a bit more robust data model on the Java side and want to hide the columns in the JTable, you can use removeColumn from JTable. This does not remove the column from the Table model, only from visible presentation. If you keep track of which columns are hidden or visible, you can easily put the column back in, and its data will still be properly associated.
For example, to remove the first column, you could use:
myTable.removeColumn(myTable.getColumnModel().get(0));
// i don't remember if it's 0-index or 1-index for first column
As an example, I would dynamically fill a JPanel with checkboxes for each column and then checking and unchecking individual boxes would hide and disable those columns. This allows you to keep all the data, but only present those relevant to the user at the time, similar to how hiding columns in Excel works.

Related

Data retrieving from a database to a table by clicking a button [duplicate]

This question already has an answer here:
How to add new rows into a jTable from database while button click without clearing existing rows
(1 answer)
Closed 5 years ago.
I want to make a POS system.
I enter a item number(in jTextField) and press button.
Then according to the item number its name and price should display in the jTable(relevant record to the item number in the database)
Then I enter another number and press button. And it also should display in the jTable without clearing existing data (as a new row)
String SQL = "SELECT name,price FROM items WHERE ID = ' "+jTextField1.getText()+" ' ";
pst = Conn.prepareStatement(sql);
rs = pst.executeQuery();
jTable1.setModel(DbUnits.resultSetToTableModel(rs));
Please help me to build this.
Note : I have already built this program. I know this isn't a freelance site !
I'm asking for a help for add new rows with data without clearing existing data.
it also should display in the jTable without clearing existing data (as a new row)
Well then you can't use the setModel(...) method since that will replace all the existing data with the new data.
And you can't use the DbUtils.resultSetToTableModel(...) method since that will return new TableModel.
Instead you will need to read the data from the ResultSet one row at a time. As you read each row you will then you can use the addRow(...) method of the DefaultTableModel to add each new row of data to the existing model.
I used this code instead of above code. But it shows javax.swing.table.DefaultTableModel#57168dd4 in the jTable.
String sql = "SELECT name,price FROM items WHERE ID = '"+jtxt1.getText()+"'";
pst = conn.prepareStatement(sql);
rs=pst.executeQuery();
DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
Vector row = new Vector();
row.add(DbUtils.resultSetToTableModel(rs));
model.addRow(row);
Help !!

How to place a JCheckBox next to every data displayed from database in Jtable using java in Netbeans?

I have to 2 tables. JTable1 and Jtable2. Jtable1 has data displayed from the database. Jtable2 should be having checkbox for every row in Jtable1. I want number of rows in Jtable2 equal Jtable1. These 2 tables are beside eachother.
Here is an example:
In this example there is a checkbox beside every data item. I want a checkbox generated in JTable2 for every data item in Jtable1.
Here is a picture to get a better idea:
Here is code:
public void fetch()
{
try
{
String sqlp = "select * from american";
pst = (OraclePreparedStatement) conn.prepareStatement(sqlp);
rs = (OracleResultSet) pst.executeQuery(sqlp);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
row =jTable1.getRowCount();
while(i!=row)
{
jTable2.add(check);
}
}
catch(Exception ex )
{
JOptionPane.showMessageDialog(null, ex);
}
}
jTable2.add(check);
You can't just add a JCheckBox to every row in the table. A table does not contain Swing components. It renders data contained in the TableModel of the table.
You need to add data (representing a check box) to the TableModel used by the table.
The DbUtils class returns a TableModel complete with data. So you have a couple of options:
Use the DefaultTableModel returned by the DbUtils class and add a new column of data to the model. Read the DefaultTableModel API. You can use the addColumn(...) method to add a new column of data to the model.
The column is added to the end of the model so you will then need to change the view of the table to display the column at the beginning of the table. You can use the moveColumn(...) method of the JTable to do this.
Finally when you create the JTable you will need to override the getColumnClass(...) method to return Boolean.class so the proper renderer/editor can be used.
Another option is to create a custom TableModel that wraps your current model with a checkbox. Check out: How to add checkbox in Jtable populated using rs2xml for an example of this approach
Finally, just don't use DbUtils, then you can be fully in control of the data in your TableModel. Check out: Java Resultset to JTable with Checkbox for an example of this approach.

Java Derby Embedded Database won't let me drop last user created table

I have an application where the user can create and delete tables in a Derby Database. I'm currently able to add as many as I want, delete as many as I want, except for the 'last' one.
For example, lets say I create the following tables: (the user creates a table by entering the name for, nothing else, no SQL Query is entered by the user)
Tables:
A, B, C.
I have these tables displayed in a JTable, and the user can select as many as they want to 'delete' by highlighting the rows.
So if highlight rows A and B, hit the delete JButton, the application deletes or DROPs them with no issue. But if I then try to delete row C, it doesn't do anything.
Same issue occurs if I select all of the rows.
This is the code that's doing the work:
public final void removeDBTable(String tableName){
try{
StringBuilder sb = new StringBuilder();
sb.append("DROP TABLE ").append(tableName);
stmt = con.createStatement();
stmt.execute(sb.toString());
stmt.close();
}catch (SQLException ex){
if(ex.getErrorCode() != 30000){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}
If anyone wants an SSCCE I can put one together, but currently don't have one ready.
TL;DR:
Can not delete/DROP last table in my database.

New ResultSet with a where, or move cursor to beginning and check condition manually

I am going to be given a staging table, which I run a process to load the data into a bigger table, and remove data from the staging table. Some rows in the staging table, denote deletions of rows in the main table though.
Right now the algorithms is as follows:
ResultSet dataToLoad = select * from ...;
ResultSet mainTable = select * from ...;
while (dataToLoad.next())
{
if(insert)
//insert this row into main table, and remove row from this table
else if(delete)
//Find the row that matches in the main table and delete it. remove row from this table
}
My question is for the delete block. Would it be best to make a new ResultSet to find the row using a where and just delete the single row in the set, or to put the cursor to the beginning and loop through the cursor checking conditions? Essentially like implementing a where clause in java code.
How much does JDBC cache when you load in a ResultSet? is it going to do a full network round trip for each cursor jump?
Lastly, I read up briefly on the Halloween Problem. Am I at risk of that here?
Why dont you try to load a List of inserts and deletes, for example
List deletesId = .....
Whie(...){
if(delete) {
deletesId.add(idDataForDeleting);
}
}
And then you can do something like:
String sql = "DELETE FROM TABLE WHERE ID IN (" + separateByComma(deletesId) + ")";
executeDelete(sql);
Of course, try to use PreparedStamment, I mean with this you will the delete operatabion in one step against the database, is better than one by one.

How to write the sql query when deleting selected row of a jtable?

I have a jtable on my GUI. (tableRealProperty). I need to add, delete and update the data inside the table. and this data are from a database where it has a primary key called ClientID. the columns inside the jtable are "Location" and "Area".
If i select a certain row from the jtable, it should be deleted as well as from the database, of course. My problem is that, when i click my delete button, not only the selected row is deleted but also all the data inside the table of that certain client..
here's my code for delete:
private void cmdDelRPropActionPerformed(java.awt.event.ActionEvent evt) {
String sql = "delete FROM tblrealProperty where tblrealproperty.ClientID = ?";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, txtClientID.getText());
((DefaultTableModel)tableRealProperty.getModel()).removeRow(tableRealProperty.getSelectedRow());
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
If i select a certain row from the jtable, it should be deleted as
well as from the database, of course. My problem is that, when i click
my delete button, not only the selected row is deleted but also all
the data inside the table of that certain client..
This sounds like you have a foreign key to tblrealproperty set on the client table with cascade delete. That means, if a client is deleted from tblrealproperty, all corresponding data with a foreign key pointed to the deleted row in tblrealproperty are deleted as well. It is a feture inside DB to prevent inconstistencies.
This query will definitely delete all the rows with particular ClientID. You have to add another column to table in database say "index" which will be unique for each row in the table. then delete the row with this index:
`delete FROM tblrealProperty where tblrealproperty.index = ?`
For me works perfectly, don't forget to check if txtClientID is an index with autoincrement in your database. If your table have similar txtClientID, your delete command execute delete of all rows with the same txtClientID.

Categories

Resources