java.sql.SQLException: Column Index out of range, 2 > 1 - java

I have a error message that I don't understand. The message is the next "java.sql.SQLException: Column Index out of range, 2 > 1"
I ask me if my problem comes from my request sql ?
String req = "Select A.CodeA from album A, collabo C where A.CodeA = C.CodeA order by 1 ";
ResultSet resu = ConnexionMySQL.getInstance().selectQuery (req);
try {
while (resu.next())
{
myList.add (new Appareil(resu.getString(1),
new Album (resu.getString(2))));
}
}
Or perhaps in my file TableModel Appareil ?I have a column "Identification" only I don't understand why it doesn't works ?
private String[] columnNames = {"Identification"};
private ArrayList <Appareil> myList;
public TableModelAppareils (ArrayList myList)
{
this.myList = myList;
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
//System.out.println("row count : " + myList.size());
return myList.size();
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
#Override
public Object getValueAt(int row, int col) {
Appareil myApp = myList.get(row);
switch (col)
{
case 0 : return myApp.getAppAlb().getCodeA();
}
return null;
}
#Override
public Class getColumnClass(int c) {
switch (c)
{
case 0 : return String.class;
}
return null;
}
public void setMyList (ArrayList myList)
{
this.myList = myList;
this.fireTableDataChanged();
}
public ArrayList <Appareil> getMyList ()
{
return myList;
}
public Appareil getMyList (int index)
{
return myList.get(index);
}
Thank you a lot

You are accessing a second column from ResultSet using resu.getString(2) in your code however you're just selecting one column A.codeA in your select query

Related

How can I add an ArrayList to a jtable?

I've been working on a web-service that returns an arraylist. How can I add the returning arraylist to jtable and display?
ArrayList customerDetails = new ArrayList();
try {
String sqlQuery = "SELECT * FROM customer WHERE AccountNumber="+accountNumber;
PreparedStatement stmt = DatabaseConnection.dBconn().prepareStatement(sqlQuery);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
customerDetails.add(rs.getString("Name"));
customerDetails.add(rs.getString("DoB"));
customerDetails.add(rs.getString("Address"));
customerDetails.add(rs.getString("Mobile"));
customerDetails.add(rs.getString("Email"));
customerDetails.add(rs.getString("AccountType"));
customerDetails.add(rs.getString("AccountNumber"));
customerDetails.add(rs.getString("SortCode"));
customerDetails.add(rs.getString("Balance"));
customerDetails.add(rs.getString("Card"));
}
return customerDetails;
} catch (SQLException err) {
System.out.println(err.getMessage());
}
return customerDetails;
Let's start with the fact that your ArrayList is not structured as a row/columns grouping, you will need a List within a List, where the outer list is the rows and the inner list are the column values
While we're at it, let's also make use of the PreparedStatement properly and manage the resources so they are closed properly while we're at it
ArrayList<List<String>> customerDetails = new ArrayList<>(25);
String sqlQuery = "SELECT * FROM customer WHERE AccountNumber=?";
try (PreparedStatement stmt = DatabaseConnection.dBconn().prepareStatement(sqlQuery)) {
stmt.setString(1, accountNumber);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
List<String> rowDetails = new ArrayList<>(10);
rowDetails.add(rs.getString("Name"));
rowDetails.add(rs.getString("DoB"));
rowDetails.add(rs.getString("Address"));
rowDetails.add(rs.getString("Mobile"));
rowDetails.add(rs.getString("Email"));
rowDetails.add(rs.getString("AccountType"));
rowDetails.add(rs.getString("AccountNumber"));
rowDetails.add(rs.getString("SortCode"));
rowDetails.add(rs.getString("Balance"));
rowDetails.add(rs.getString("Card"));
customerDetails.add(rowDetails);
}
}
} catch (SQLException err) {
System.out.println(err.getMessage());
}
return customerDetails;
Have a look at Using Prepared Statements and The try-with-resources Statement for more details
Now, we need a TableModel which can support it, at very basic level...
public class ListTableModel extends AbstractTableModel {
private List<List<String>> rows;
private List<String> columnNames;
public ListTableModel(List<String> columnNames, List<List<String>> rows) {
this.rows = new ArrayList<>(rows);
this.columnNames = columnNames;
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public int getColumnCount() {
return columnNames.size();
}
#Override
public String getColumnName(int column) {
return columnNames.get(column);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Class type = String.class;
return type;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
List<String> rowData = rows.get(rowIndex);
return rowData.get(columnIndex);
}
}
This takes a List for the column names and a List<List> for the row data.
Personally, I'd prefer to wrap the data into some kind of Plain Old Java Object (POJO) as it encapsulates the data and provides greater flexibility when displaying it (ie, I need to display all the properties of the object if I don't want to)
Take a look at How to Use Tables for more details

Hibernate gives a strange ClassCast exception (using Transformers)

This code:
#Override
public List<FactCodeDto> getAllFactsWithoutParentsAsFactDto() {
String completeQuery = FactCodeQueries.SELECT_DTO_FROM_FACT_WITH_NO_PARENTS;
Query query = createHibernateQueryForUnmappedTypeFactDto(completeQuery);
List<FactCodeDto> factDtoList = query.list(); //line 133
return factDtoList;
}
calling this method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}
gives me a ClassCastException -> part of the trace:
Caused by: java.lang.ClassCastException: org.bamboomy.cjr.dto.FactCodeDto cannot be cast to java.util.Map
at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
at org.hibernate.hql.internal.HolderInstantiator.instantiate(HolderInstantiator.java:75)
at org.hibernate.loader.custom.CustomLoader.getResultList(CustomLoader.java:435)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423)
at org.hibernate.loader.Loader.list(Loader.java:2418)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1898)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:318)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at org.bamboomy.cjr.dao.factcode.FactCodeDAOImpl.getAllFactsWithoutParentsAsFactDto(FactCodeDAOImpl.java:133)
Which is pretty strange because, indeed, if you look up the source code of Hibernate it tries to do this:
#Override
#SuppressWarnings("unchecked")
public void set(Object target, Object value, SessionFactoryImplementor factory) {
( (Map) target ).put( propertyName, value ); //line 102
}
Which doesn't make any sense...
target is of type Class and this code tries to cast it to Map,
why does it try to do that???
any pointers are more than welcome...
I'm using Hibernate 5 (and am upgrading from 3)...
edit: I also use Spring (4.2.1.RELEASE; also upgrading) which calls these methods upon deploy, any debugging pointers are most welcome as well...
edit 2: (the whole FactCodeDto class, as requested)
package org.bamboomy.cjr.dto;
import org.bamboomy.cjr.model.FactCode;
import org.bamboomy.cjr.model.FactCodeType;
import org.bamboomy.cjr.utility.FullDateUtil;
import org.bamboomy.cjr.utility.Locales;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.util.Assert;
import java.util.*;
#Getter
#Setter
#ToString
public class FactCodeDto extends TreeNodeValue {
private String cdFact;
private String cdFactSuffix;
private Boolean isSupplementCode;
private Boolean isTitleCode;
private Boolean mustBeFollowed;
private Date activeFrom;
private Date activeTo;
private Boolean isCode;
private Long idFact;
private Long idParent;
private String type;
Map<Locale, String> description = new HashMap<Locale, String>(3);
public FactCodeDto() {
}
public FactCodeDto(String prefix, String suffix) {
super();
this.cdFact = prefix;
this.cdFactSuffix = suffix;
}
public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode, Boolean mustBeFollowed) {
super();
this.cdFact = cdFact;
this.cdFactSuffix = cdFactSuffix;
this.isSupplementCode = isSupplementCode;
this.mustBeFollowed = mustBeFollowed;
}
public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode, Boolean mustBeFollowed, Long idFact, Long idParent, Boolean isCode, Boolean isTitleCode, Date from, Date to, Map<Locale, String> descriptions,String type) {
super();
this.cdFact = cdFact;
this.cdFactSuffix = cdFactSuffix;
this.isSupplementCode = isSupplementCode;
this.mustBeFollowed = mustBeFollowed;
this.idFact = idFact;
this.idParent = idParent;
this.isCode = isCode;
this.isTitleCode = isTitleCode;
this.activeFrom = from;
this.activeTo = to;
if (descriptions != null) {
this.description = descriptions;
}
this.type = type;
}
public FactCodeDto(FactCode fc) {
this(fc.getPrefix(), fc.getSuffix(), fc.isSupplementCode(), fc.isHasMandatorySupplCodes(), fc.getId(), fc.getParent(), fc.isActualCode(), fc.isTitleCode(), fc.getActiveFrom(), fc.getActiveTo(), fc.getAllDesc(),fc.getType().getCode());
}
public String formatCode() {
return FactCode.formatCode(cdFact, cdFactSuffix);
}
public boolean isActive() {
Date now = new Date(System.currentTimeMillis());
return FullDateUtil.isBetweenDates(now, this.activeFrom, this.activeTo);
}
public void setDescFr(String s) {
description.put(Locales.FRENCH, s);
}
public void setDescNl(String s) {
description.put(Locales.DUTCH, s);
}
public void setDescDe(String s) {
description.put(Locales.GERMAN, s);
}
/**
* public String toString() {
* StringBuilder sb = new StringBuilder();
* sb.append(getIdFact() + ": ")
* .append(getIdParent() + ": ")
* .append(" " + cdFact + cdFactSuffix + ": " + (isSupplementCode ? "NO Principal " : " Principal "))
* .append((mustBeFollowed ? " Must Be Followed " : "NOT Must Be Followed "));
* return sb.toString();
* }
*/
public Map<Locale, String> getDescription() {
return description;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
String fullCode = formatCode();
result = prime * result + ((fullCode == null) ? 0 : fullCode.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FactCodeDto other = (FactCodeDto) obj;
return formatCode().equals(other.formatCode());
}
#Override
public boolean isChildOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isChild = false;
if (value instanceof FactCodeDto) {
if (this.getIdParent() != null) {
isChild = this.getIdParent().equals(((FactCodeDto) value).getIdFact());
}
}
return isChild;
}
#Override
public boolean isBrotherOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isBrother = false;
if (value instanceof FactCodeDto) {
if (this.getIdParent() != null) {
isBrother = this.getIdParent().equals(((FactCodeDto) value).getIdParent());
}
}
return isBrother;
}
#Override
public boolean isParentOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isParent = false;
if (value instanceof FactCodeDto) {
isParent = this.getIdFact().equals(((FactCodeDto) value).getIdParent());
}
return isParent;
}
#Override
public int compareTo(TreeNodeValue to) {
if (to instanceof FactCodeDto) {
return formatCode().compareTo(((FactCodeDto) to).formatCode());
} else return 1;
}
public String getCode() {
return formatCode();
}
}
I found that AliasToBean has changed in Hibernate 5. For me adding getter for my field fixed the problem.
This exception occurs when the setters and getters are not mapped correctly to the column names.
Make sure you have the correct getters and setters for the query(Correct names and correct datatypes).
Read more about it here:
http://javahonk.com/java-lang-classcastexception-com-wfs-otc-datamodels-imagineexpirymodel-cannot-cast-java-util-map/
I do some investigation on this question. The problem is that Hibernate converts aliases for column names to upper case — cdFact becomesCDFACT.
Read for a more deeply explanation and workaround here:
mapping Hibernate query results to custom class?
In the end it wasn't so hard to find a solution,
I just created my own (custom) ResultTransformer and specified that in the setResultTransformer method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(new FactCodeDtoResultTransformer());
//return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}
the code of the custom result transformer:
package org.bamboomy.cjr.dao.factcode;
import org.bamboomy.cjr.dto.FactCodeDto;
import java.util.Date;
import java.util.List;
/**
* Created by a162299 on 3-11-2015.
*/
public class FactCodeDtoResultTransformer implements org.hibernate.transform.ResultTransformer {
#Override
public Object transformTuple(Object[] objects, String[] strings) {
FactCodeDto result = new FactCodeDto();
for (int i = 0; i < objects.length; i++) {
setField(result, strings[i], objects[i]);
}
return result;
}
private void setField(FactCodeDto result, String string, Object object) {
if (string.equalsIgnoreCase("cdFact")) {
result.setCdFact((String) object);
} else if (string.equalsIgnoreCase("cdFactSuffix")) {
result.setCdFactSuffix((String) object);
} else if (string.equalsIgnoreCase("isSupplementCode")) {
result.setIsSupplementCode((Boolean) object);
} else if (string.equalsIgnoreCase("isTitleCode")) {
result.setIsTitleCode((Boolean) object);
} else if (string.equalsIgnoreCase("mustBeFollowed")) {
result.setMustBeFollowed((Boolean) object);
} else if (string.equalsIgnoreCase("activeFrom")) {
result.setActiveFrom((Date) object);
} else if (string.equalsIgnoreCase("activeTo")) {
result.setActiveTo((Date) object);
} else if (string.equalsIgnoreCase("descFr")) {
result.setDescFr((String) object);
} else if (string.equalsIgnoreCase("descNl")) {
result.setDescNl((String) object);
} else if (string.equalsIgnoreCase("descDe")) {
result.setDescDe((String) object);
} else if (string.equalsIgnoreCase("type")) {
result.setType((String) object);
} else if (string.equalsIgnoreCase("idFact")) {
result.setIdFact((Long) object);
} else if (string.equalsIgnoreCase("idParent")) {
result.setIdParent((Long) object);
} else if (string.equalsIgnoreCase("isCode")) {
result.setIsCode((Boolean) object);
} else {
throw new RuntimeException("unknown field");
}
}
#Override
public List transformList(List list) {
return list;
}
}
in hibernate 3 you could set Aliasses to queries but you can't do that anymore in hibernate 5 (correct me if I'm wrong) hence the aliasToBean is something you only can use when actually using aliasses; which I didn't, hence the exception.
Im my case :
=> write sql query and try to map result to Class List
=> Use "Transformers.aliasToBean"
=> get Error "cannot be cast to java.util.Map"
Solution :
=> just put \" before and after query aliases
ex:
"select first_name as \"firstName\" from test"
The problem is that Hibernate converts aliases for column names to upper case or lower case
I solved it by defining my own custom transformer as given below -
import org.hibernate.transform.BasicTransformerAdapter;
public class FluentHibernateResultTransformer extends BasicTransformerAdapter {
private static final long serialVersionUID = 6825154815776629666L;
private final Class<?> resultClass;
private NestedSetter[] setters;
public FluentHibernateResultTransformer(Class<?> resultClass) {
this.resultClass = resultClass;
}
#Override
public Object transformTuple(Object[] tuple, String[] aliases) {
createCachedSetters(resultClass, aliases);
Object result = ClassUtils.newInstance(resultClass);
for (int i = 0; i < aliases.length; i++) {
setters[i].set(result, tuple[i]);
}
return result;
}
private void createCachedSetters(Class<?> resultClass, String[] aliases) {
if (setters == null) {
setters = createSetters(resultClass, aliases);
}
}
private static NestedSetter[] createSetters(Class<?> resultClass, String[] aliases) {
NestedSetter[] result = new NestedSetter[aliases.length];
for (int i = 0; i < aliases.length; i++) {
result[i] = NestedSetter.create(resultClass, aliases[i]);
}
return result;
}
}
And used this way inside the repository method -
#Override
public List<WalletVO> getWalletRelatedData(WalletRequest walletRequest,
Set<String> requiredVariablesSet) throws GenericBusinessException {
String query = getWalletQuery(requiredVariablesSet);
try {
if (query != null && !query.isEmpty()) {
SQLQuery sqlQuery = mEntityManager.unwrap(Session.class).createSQLQuery(query);
return sqlQuery.setResultTransformer(new FluentHibernateResultTransformer(WalletVO.class))
.list();
}
} catch (Exception ex) {
exceptionThrower.throwDatabaseException(null, false);
}
return Collections.emptyList();
}
It worked perfectly !!!
Try putting Column names and field names both in capital letters.
This exception occurs when the class that you specified in the AliasToBeanResultTransformer does not have getter for the corresponding columns. Although the exception details from the hibernate are misleading.

Why does JTable only present 1st row of data?

I'm starting to learn how to use databases and was trying to export the data from my h2 database into a JTable. The table comes up with the correct number of rows, however, only the first row is filled with data. The rest is a blank grid. I posted some code below for the JTable. If someone needs to see more code, I'll post it.
public class Table extends JTable{
public static int rows;
public static String[][] data;
public static String[] columns = {"Author", "Customer", "Date"};
public static void populateTable() throws ClassNotFoundException, SQLException{
//Server is name of the database class
Server server = new Server();
Statement stat = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stat.executeQuery("SELECT * FROM data");
rs.last();
rows = rs.getRow();
rs.beforeFirst();
data = new String[3][rows];
while(rs.next()){
int i = 0;
data[0][i] = rs.getString("Author");
data[1][i] = rs.getString("Customer");
data[2][i] = rs.getString("Date");
System.out.println(rs.getString("Author"));
i = i++;
}
rs.close();
}
}
class MyTableModel extends DefaultTableModel{
String[] columnNames = {"Author", "Customer", "Date"};
MyTableModel() throws ClassNotFoundException, SQLException{
addColumn(columnNames[0]);
addColumn(columnNames[1]);
addColumn(columnNames[2]);
}
#Override
public int getRowCount() {
return rows;
}
#Override
public int getColumnCount() {
return 3;
}
#Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[columnIndex][rowIndex];
}
I'm also able to print to the console all the data, but it just won't show up in the JTable. I have been stuck on this problem for hours but I don't know what I'm doing wrong. Thanks in advance
This statement is a no-op since i is assigned before it is incremented
i = i++;
just use
i++;
Also initialize i before entering the loop
You should either use a for loop or declare i outside of your loop. As it stands, you are setting all data to row 0 (int i = 0);
while(rs.next()){
int i = 0; // this will run for every row
data[0][i] = rs.getString("Author");
data[1][i] = rs.getString("Customer");
data[2][i] = rs.getString("Date");
System.out.println(rs.getString("Author"));
i = i++;
}

how to list an items to a JTable

I am trying to create a checkout simulation for my coursework. So every time I search for an item I can retrieve it from the database and display it on the JTable. However, once I add an item to the list and try to add another item the old item get replaced by the new item.
I am trying to list all the item in the JTable, this is my code:
DBConnection db = new DBConnection();
try {
ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '"+ id + "'");
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
System.out.println(e);
}`
The main problem is DbUtils.resultSetToTableModel(rs), which is creating a brand new TableModel, filled with the contents of the ResultSet, this, when applied to the JTable is replacing the view with the contents of the TableModel.
In order to be able to update the table, you need to update the existing TableModel...
There are a few ways this might be achieved, by the simplest might be to use a DefaultTableModel...
Start by creating a class instance field of a DefaultTableModel...
public class ... {
//...
private DefaultTableModel stockTableModel;
//...
Then, when you want to load the stock items, you will need to initialise the model, if it's not already initialised, and then add the new results to it...
DBConnection db = new DBConnection();
try (ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '" + id + "'")) {
if (stockTableModel == null) {
stockTableModel = new DefaultTableModel();
for (int col = 0; col < metaData.getColumnCount(); col++) {
stockTableModel.addColumn(metaData.getColumnName(col + 1));
}
jTable.setModel(model);
}
while (rs.next()) {
Vector rowData = new Vector(metaData.getColumnCount());
for (int col = 0; col < metaData.getColumnCount(); col++) {
rowData.add(rs.getObject(col + 1));
}
stockTableModel.addRow(rowData);
}
} catch (SQLException exp) {
exp.printStackTrace();
}
Take a look at How to Use Tables and JDBC Database Access for more details
You can create a custom data model that allows you to insert new rows to table.
lets say that you have class, that can hold your query result fields.
public class Item implements Comparable<Item> {
private Long id;
private String message;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
public String getMessage() {
return message;
}
public void setMessage(String value) {
this.message= value;
}
#Override
public int compareTo(Item o) {
return id.compareTo(o.id);
}
}
and it needs to go to table, which has been defined somewhere like:
JTable table =new JTable();
this is a data model to your table
public class Model extends AbstractTableModel {
private List<Item> items;
public Model() {
items = new ArrayList<>();
}
#Override
public int getRowCount() {
return items.size();
}
#Override
public int getColumnCount() {
return 3;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex > items.size() - 1 || rowIndex < 0) {
return "";
}
final Item get = items.get(rowIndex);
switch (columnIndex) {
case 0:
return get.getId();
case 1:
return get.getMessage();
}
return "";
}
#Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "id";
case 1:
return "message";
}
return "";
}
public void addItem(Item i) {
items.add(i);
fireTableDataChanged();
}
public void addItem(ResultSet rs) {
try {
Item item = new Item();
item.setId(rs.getLong("ID"));
item.setMessage(rs.getString("MESSAGE"));
items.add(item);
fireTableDataChanged();
} catch (SQLException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
now create field
Model myModel=new Model();
and set it as a table model
table.setModel(myModel);
now every time you need to add something to table, just use our table model (i created two methods to insert data public void addItem(Item i) and public void addItem(ResultSet rs).
this should work. If you need to clear table sometimes, just add pubic method public void clear() to your model, in which you will clear items list and call fireTableDataChanged();. It is necessary, otherwise GUI will not refresh.
EDIT
Your code should be like
DBConnection db = new DBConnection();
try {
ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '" + id + "'");
myModel.add(rs);
} catch (Exception e) {
System.out.println(e);
}
Just add a row to your JTable Model every time you have your result...
refer to this SO question
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
or in your case
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{searchResultData});

Definition TableModel removeRow() method [duplicate]

This question already has an answer here:
TableModel removeRow() definition [closed]
(1 answer)
Closed 9 years ago.
This is my tableModel:
public class d9 extends AbstractTableModel {
ArrayList<String> cols = new ArrayList<>();
ArrayList<ArrayList<String>> data = new ArrayList<>();
public d9() {
...
int c = resultSet.getMetaData().getColumnCount();
while (resultSet.next()) {
ArrayList<String> eachRow = new ArrayList<>();
for (int i = 1; i <= c; i++) {
eachRow.add(resultSet.getString(i));
}
data.add(eachRow);
}
...
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return cols.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
ArrayList<String> selectedRow = data.get(rowIndex);
return selectedRow.get(columnIndex);
}
#Override
public String getColumnName(int column) {
return cols.get(column);
}
public void removeRow(int rowNumber) {
data.remove(rowNumber);
fireTableRowsDeleted(rowNumber, rowNumber);
}
}
Now, after passing a convertRowIndexToModel line number to removeRow method
Row remove from table, But after re-run program, It come back!
When you call removeRow you need to try and remove the row from the database.
Now because I have no idea what the structure of your database is, you will need to fill in the details, but this a simple outline of what you need to do
public void removeRow(int rowNumber) throws SQLException {
Connection con = ...;
PreparedStatement ps = null;
String keyValue = ...; // Get key value from the ArrayList
try {
ps = con.prepareStatement("DELETE from youDatabaseTabe where key=?");
ps.setObject(1, keyValue);
if (ps.executeUpdate() == 1) {
data.remove(rowNumber);
fireTableRowsDeleted(rowNumber, rowNumber);
} else {
throw new SQLException("Failed to remove row from database");
}
} finally {
try {
ps.close();
} catch (Exception e) {
}
}
}
You may want to spend some time having a read through JDBC Database Access

Categories