How to remove duplicate rows from JTable? - java

In this class, I am trying to only keep one of each value in the JTable. The Data is coming from a Database. I dont need repetative data though.
public JTable getHeute(){
DBconnect verbinden = new DBconnect();
verbinden.erstelleVerbindung();
JTable Habwesend=new JTable();
Habwesend.setBounds(10, 30, 290, 400);
Habwesend.setEnabled(false);
DefaultTableModel dm=new DefaultTableModel();
try {
ResultSet rs= verbinden.sqlStatement.executeQuery("select MA_ID from AB_Spanne where(Date() >= Start and Date() <= Ende)");
ResultSetMetaData rsmd=rs.getMetaData();
//Coding to get columns-
int cols=rsmd.getColumnCount();
String c[]=new String[cols];
for(int i=0;i<cols;i++){
c[i]=rsmd.getColumnName(i+1);
for (int k = 0; k < c.length; k++) {
dm.addColumn(c[k]);
}
}
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
Habwesend.setModel(dm);
verbinden.schliesseVerbindung();
}

Change your query to:
"SELECT DISTINCT MA_ID from AB_Spanne where(Date() >= Start and Date() <= Ende)"
You can do it in java like (unrecommended and unperformant):
//UNTESTED CODE
List<Object> Objectlist = new List<Object>();
// ...
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
if !(Objectlist.Contains(row)){
dm.addRow(row);
}
}
// I guess in order to the contains methode to work you may need to create own objects in which you override the equality / comparrision methods.

Instead of the List, use a Set and keep the rest of your code the same. That's your java solution, to whit:
// Set dm = new HashSet();
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
Habwesend.setModel(dm);
verbinden.schliesseVerbindung();

Related

SQL Exception When Sending values from jtable to sql

I am stuck in a problem. When I try to send data from jtable to sql database through stored procedure. here what I am doing:
inserting data to jtable
String b= jLabel116.getText(),c=jTextField6.getText(),e=jTextField20.getText(),f=jTextField25.getText(),g=jTextField48.getText();
float x,y,z;
x=Float.parseFloat(jTextField25.getText());
y=Float.parseFloat(jTextField48.getText());
z=x*y;
String total1=String.valueOf(z);
DefaultTableModel df = (DefaultTableModel) jTable5.getModel();
df.addRow(new Object[]{b,c,d,f,g,total1});
int rowsCount = jTable5.getRowCount();
int Price = 0,Qty=0, total=0;
for(int i=0;i<rowsCount;i++){
Price += Integer.parseInt(jTable5.getValueAt(i,3).toString());
Qty += Integer.parseInt(jTable5.getValueAt(i,4).toString());
}
total = Price*Qty;
System.out.println(total);
jTextField26.setText(String.valueOf(total));
jTextField51.setText(String.valueOf(total));
jTextField50.setText(String.valueOf(Qty));
jTable5.setModel(df);
Sending Data to Database
try{
DefaultTableModel df = new DefaultTableModel();
df=(DefaultTableModel) jTable5.getModel();
CallableStatement cs=m.XC.prepareCall("call Prod_SALE (?,?,?,?,?,?,?,?)");
for (int i = 0; i < df.getRowCount(); i++) {
for (int j = 0; j < df.getColumnCount(); j++) {
Object o = df.getValueAt(i, j);
System.out.println("object from table is : " +o);
cs.setString(j+1, (String)o);
cs.addBatch();
}
cs.executeBatch();
cs.clearParameters();
}
}
catch(Exception ex){
ex.printStackTrace();
Error Exception:
java.sql.SQLException: Parameter-Set has missing values.
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.addBatch(JdbcOdbcPreparedStatement.java:1546)
Please help me....I am unable to solve it
You call addBatch in the inner loop (variable j) after you have set one parameter. Obviously this fails since you have 8 parameters. The Javadoc of PreparedStatement.addBatch says:
Adds a set of parameters to this PreparedStatement object's batch of
commands.
You need to move the call to addBatch out of the inner loop.
(And probably the executeBatch should be moved out of the outer loop (variable i) too.
DefaultTableModel df = (DefaultTableModel) jTable5.getModel();
CallableStatement cs=m.XC.prepareCall("call Prod_SALE (?,?,?,?,?,?,?,?)");
for (int i = 0; i < df.getRowCount(); i++)
{
for (int j = 0; j < df.getColumnCount(); j++)
{
Object o = df.getValueAt(i, j);
System.out.println("object from table is : " +o);
cs.setString(j+1, (String)o);
}
cs.addBatch();
}
cs.executeBatch();
As the message says, you have not set all values in your SQL.

ArrayIndexOutOfBoundsException error but I think the code is okay

So I have a function that populates JTable from my database.
I have here
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> newRow = new Vector<Object>();
for (int i = 1; i <= numberOfColumns; i++) {
if(isObjectInteger(rs.getObject(i)) && i>1) //checks if the value is Integer else not and is past the first column
{
System.out.println(i+"="+rs.getObject(i));
String label = columnNames.get(i); //THE ERROR IS ON THIS PART
newRow.addElement(getValue((Integer) rs.getObject(i),label)); //gets the value of specific foreign key id from another table
}
else
{
System.out.println(i+"="+rs.getObject(i));
newRow.addElement(rs.getObject(i));
} //inside row (new Rows)
}
rows.addElement(newRow); //outside row
}
return new DefaultTableModel(rows, columnNames)
{
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I have total 8 columns in my database the output of that System.out.println is:
The one's that get's inside the else:
1=1
2=test
3=A.
4=test
5=test
6=test
The one's that get's inside the if
7=1
8=23
As you can see the output is right but it always throws Array index out of range: 8 error on the String label = columnNames.get(i);
While ResultSet.getObject() requires an argument based on one, columnNames is a vector, with its indexes based on zero.
Hence valid values for it would be 0..7, not 1..8. In other words, the first part of your if statement should be:
System.out.println(i + "=" + rs.getObject(i));
String label = columnNames.get(i-1); // NOT "i".

Copy selected data from a jtable in frame1 to another table in frame2

I have a JTable2 in frame1 and JTable1 in frame2. I want to copy and send selected data from table2 to table1. how do i do it ?
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
String sql = "select * from table1 where Bill_No like '"+jTextField2.getText()+"'";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
JFrame NewJFrame2 = new NewJFrame2();
NewJFrame2.setVisible(true);
int i=0;
while(rs.next()) {
Object bno = rs.getString("Bill No");
Object bamount = rs.getString("Bill Amount");
Object btds = rs.getString("TDS");
Object btax = rs.getString("Tax");
Object bpayable = rs.getString("Payable");
jTable1.getModel().setValueAt(bno,i, 0 );
jTable1.getModel().setValueAt(bamount, i, 1);
jTable1.getModel().setValueAt(btds, i, 2);
jTable1.getModel().setValueAt(btax, i, 3);
jTable1.getModel().setValueAt(bpayable, i, 4);
System.out.println(i);
i++;
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Start by having a look at How to Use Tables.
If you want to "copy" the selected data, then you will need to know what rows are selected, see JTable#getSelectedRows.
You're making life difficult for yourself using DbUtils as you've lost the ability to just transfer the objects from one model to another.
The basic idea would be to copy the values from the original table into a new TableModel and pass that to the second window, something like
TableModel original = table.getModel();
DefaultTableModel model = new DefaultTableModel(table.getSelectedRowCount(), original.getColumnCount());
for (int col = 0; col < original.getColumnCount(); col++) {
model.addColumn(original.getColumnName(col));
}
int[] selectedRows = table.getSelectedRows();
for (int targetRow = 0; targetRow < selectedRows.length; targetRow++) {
int row = selectedRows[targetRow];
int modelRow = table.convertRowIndexToModel(row);
for (int col = 0; col < original.getColumnCount(); col++) {
model.setValueAt(original.getValueAt(modelRow, col), targetRow, col);
}
}
for example. Now you just need to pass model to the second window and apply it to the JTable contained within

I cant view data in JTable From a custom table model

Here is my code:
Object[][] refreshCartonCodesToTable = dbutils.checker.CartonCodesToTable();
String[] colnames = new String[6];
colnames[0] = selectCodes.invoiceTable.getColumnName(0).toString();
colnames[1] = selectCodes.invoiceTable.getColumnName(1).toString();
colnames[2] = selectCodes.invoiceTable.getColumnName(2).toString();
colnames[3] = selectCodes.invoiceTable.getColumnName(3).toString();
colnames[4] = selectCodes.invoiceTable.getColumnName(4).toString();
colnames[5] = selectCodes.invoiceTable.getColumnName(5).toString();
MyTableModel mod = new MyTableModel(refreshCartonCodesToTable, colnames);
selectCodes.invoiceTable = new JTable(mod);
selectCodes.invoiceTable.setVisible(true);
Custom model as shown below:
class MyTableModel extends DefaultTableModel {
public MyTableModel(Object data[][], Object columnames[]) {
super(data, columnames);
}
public Class getColumnClass(int col) {
if (col == 5) {
return Boolean.class;
} else {
return String.class;
}
}
#Override
public boolean isCellEditable(int row, int col) {
if (col == 0) //first column will be uneditable
{
return false;
} else {
return true;
}
}
}
The table displays the columnames but the data is not diplayed. The array has data and the sample output is as shown below:
250VV 250VV0575W20140819 false B1 19 August 2014
250VV 250VV0561W20140819 false B1 19 August 2014
250VV 250VV0560W20140819 false B1 19 August 2014
250VV 250VV0559W20140819 false B1 19 August 2014
250VV 250VV0558W20140819 false B1 19 August 2014
There are six columns. The sixth column I want to place a checkbox in the cells.
Can somebody help me please.
Here is the source code for CartonCodesToTable();
public static Object[][] CartonCodesToTable() {
Object[][] array = null;
try {
dbutils.checker.connect_to_db_again_again();
sqlcommand = "SELECT Product_ID, carton_code, scanned, batchno,date FROM carton_codes where scanned ='false' order by bno asc";
rset = stmts.executeQuery(sqlcommand);
int row = 0;
while (rset.next()) {
rset.last();
row = rset.getRow();
}
array = new String[row][6];
rset.beforeFirst();
int x = 0;
while (rset.next()) {
array[x][0] = rset.getObject("Product_ID");
array[x][1] = rset.getObject("carton_code");
array[x][2] = rset.getObject("scanned");
array[x][3] = rset.getObject("batchno");
array[x][4] = rset.getObject("date");
array[x][5] = false;
x += 1;
}
conn.close();
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
return array;
}
When i use array[x][5] = false; i get an error 'java.lang.ArrayStoreException: java.lang.Boolean' So i decided to use array[x][5] = "false";
You haven't provided an MCVE like I suggested, so there's hard to tell what's going on. First thing I see though is poor use of the ResultSet you don't need to do all those things. For example your use of rs.last().
boolean last() throws SQLException - Moves the cursor to the last row in this ResultSet object.
About ResultSet from API
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable (See the API for an example how to do this)
So assuming you haven't make the ResultSet scrollable, that would explain you getting no results, as you have moved the cursor to the end with the call to rs.last()
That being said, you don't need to get the row count. Use a dynamic data structure to create the model instead. Just use a Vector. If you use an array for the data, DefaultTableModel will convert it to a Vector (under the hood) anyway.
A common approach is to make use of the ResultSetMetaData class and get the column count and create a Vector<Vector<Object>> dynamically and construct you DefaultTableModel that way. Something like:
public DefaultTableModel getModelFromResultSet(ResultSet rs) throws Exception {
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
String[] cols = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
col[i - 1] = md.getColumnName(i);
}
Vector<Vector<Object>> dataVector = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> row = Vector<Object>();
for (int i = 1; i <= columnCount; i++) {
row.add(rs.getObject(i));
}
dataVector.add(row);
}
DefaultTableModel model = new DefaultTableModel(dataVector, cols) {
#Override
public Class<?> getColumnClass(int column) {
...
}
};
return model;
}
Or something like this. Haven't tested it (for any errors), but the basic concept is there.
As far as your ArrayStoreException, look at what you're doing
Object[][] array = null;
...
array = new String[row][6];
What's the point of doing this. You are making it every object has to be a String. Which may not be desirable for rendering.

ArrayList.size() returning incorrect value

I have a strange error which I can not get my head around where the .size() method does not appear to return the correct value.
This first bit of code creates the ArrayList.
public void createResultList(String query) {
ArrayList<ArrayList<String>> data = new ArrayList();
try {
ResultSet rs = st.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
for(int i = 0; i < meta.getColumnCount(); i++) {
data.add(i, new ArrayList<String>());
}
int x = 0;
while(rs.next()) {
for(int y = 0; y < meta.getColumnCount(); y++) {
data.get(x).add(rs.getString(y + 1));
}
x++;
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
ResultTable result = new ResultTable(data);
JTable table = new JTable(result);
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
refresh();
}
This is my TableModel class which is used to create the table when it's passed to it.
public class ResultTable extends AbstractTableModel {
private ArrayList<ArrayList<String>> data;
public ResultTable(ArrayList<ArrayList<String>> data) {
this.data = data;
}
public int getColumnCount() {
return data.get(0).size();
}
public int getRowCount() {
return data.size();
}
public Object getValueAt(int row, int col) {
return data.get(row).get(col);
}
}
Now the the problem is in the ResultTable class, now for a select query returning one row with 12 columns, the first data.get(0).size() call correctly returns 12, but the 2nd data.size() call incorrectly returns 12 also instead of 1, this is causing out of bounds errors, can anyone please explain this seemingly paradoxical result?
This is something you should've found easily when you debug your code...
public void createResultList(String query) {
ArrayList<ArrayList<String>> data = new ArrayList();
data is an ArrayList of ArrayLists
try {
ResultSet rs = st.executeQuery(query);
A query returning 1 row of 12 columns
ResultSetMetaData meta = rs.getMetaData();
for(int i = 0; i < meta.getColumnCount(); i++) {
For each column in your recordset, being 12, you add an empty ArrayList in data
data.add(i, new ArrayList<String>());
}
resulting in data being an ArrayList of 12 empty Arraylists
This already explains why data.size() == 12
int x = 0;
while(rs.next()) {
for each record in your recordset, being 1
for(int y = 0; y < meta.getColumnCount(); y++) {
for each column in your recordset, being 12, you add a string to the ArrayList with the same index as the recordset
data.get(x).add(rs.getString(y + 1));
}
The first ArrayList in data (data.get(0)) will have 12 Strings
All other ArrayLists in data (data.get(x) where x > 0) will remain empty
x++;
}
Resulting in data being an ArrayList of 12 ArrayLists
of which only the first ArrayList has 12 Strings and the others are empty
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
ResultTable result = new ResultTable(data);
JTable table = new JTable(result);
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
refresh();
}
When you create the data list, you create a sublist to hold the data for each column.
If that is what you want to do, you should add data from each column of the result set to the list that corresponds to it:
while(rs.next()) {
for(int y = 0; y < meta.getColumnCount(); y++) {
data.get(y).add(rs.getString(y + 1));
}
}

Categories