I have two result sets coming from two different database and I need to compare it. I want an operation like
A-B
to be performed on them.
I cannot perform row by row comparison as 1st row in A resultset can be present anywhere in B resultset.
Below is the code to do that in .NET, which is very easy and perfect .
var nonIntersecting = dtSource.AsEnumerable().Except
(
dtTarget.AsEnumerable(), DataRowComparer.Default
);
try
{
dtSrcToTgtResult = nonIntersecting.CopyToDataTable();
} catch (InvalidOperationException ex) {}
Here dtSource,dtTarget are datatables having source and target data from databases.
dtSrcToTgtResult contains data present in source but not in target, which is exactly what I want.
Can same be done in JavaScript with result sets. I can also check CachedRowSet or webRowSet if something like this is available in it.
EDIT
For people who are giving minus votes. this is what i already did, but its not solving the problem.
private Boolean compare(ResultSet rsSrc,ResultSet rsTgt,String ExecCondition)
{
Boolean status = true;
try
{
ResultSetMetaData metaSrc = rsSrc.getMetaData();
ResultSetMetaData metaTgt = rsTgt.getMetaData();
final int columnCountSrc = metaSrc.getColumnCount();
List<DBRow> dList = new ArrayList<DBRow>();
List<DBRow> DataInSourceNotInTarget = new ArrayList<DBRow>();
List<DBRow> DataInTargetNotInSource = new ArrayList<DBRow>();
DBRow d = new DBRow();
DBRow d1 = new DBRow();
for (int column = 1; column <= columnCountSrc; column++)
{
d.Row.add(metaSrc.getColumnName(column));
d1.Row.add(metaTgt.getColumnName(column));
}
DataInSourceNotInTarget.add(d);
DataInTargetNotInSource.add(d1);
if(ExecCondition.equals("Source To Target"))
{
while(rsSrc.next())
{
if(rsTgt.next())
{
for (int column = 1; column <= columnCountSrc; column++)
{
Object valueSrc = rsSrc.getObject(column);
Object valueTgt = rsTgt.getObject(column);
if(!valueSrc.toString().equals(valueTgt.toString()))
{
status=false;
System.out.println("ValueSRC: "+v alueSrc.toString());
System.out.println("ValueTgt: "+valueTgt.toString());
}
}
}
else
{
// if target rows ends
DBRow dr = new DBRow();
for (int column = 1; column <= columnCountSrc; column++)
{
Object valueSrc = rsSrc.getObject(column);
dr.Row.add(valueSrc);
}
DataInSourceNotInTarget.add(dr);
}
}
}//exec condition if
if(ExecCondition.equals("Target To Source"))
{
while(rsTgt.next())
{
if(rsSrc.next())
{
for (int column = 1; column <= columnCountSrc; column++)
{
Object valueSrc = rsSrc.getObject(column);
Object valueTgt = rsTgt.getObject(column);
if(!valueSrc.toString().equals(valueTgt.toString()))
{
status=false;
System.out.println("ValueSRC: "+valueSrc.toString());
System.out.println("ValueTgt: "+valueTgt.toString());
}
}
}
else
{
// if Source rows ends
DBRow dr = new DBRow();
for (int column = 1; column <= columnCountSrc; column++)
{
Object valueTgt = rsTgt.getObject(column);
dr.Row.add(valueTgt);
}
DataInTargetNotInSource.add(dr);
}
}
for(DBRow obj:DataInTargetNotInSource)
{
obj.print();
}
}//exec condition if
}
catch(Exception e)
{
e.printStackTrace();
}
return status;
}
I have a solution that is functional but not optimal:
It requires to load all rows into in-memory data structures (each ResultSet is loaded into list, each item is map of column name-value)
loop on source rows' list and for every item in that list - search that it does not exist in target list (meaning o(n^2) processing)
I used Apache DbUtils to easily convert ResultSet to List.
import java.sql.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.dbutils.handlers.MapListHandler;
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// load source table
Statement st = conn.createStatement();
ResultSet sourceRs = st.executeQuery("SELECT * FROM source");
List<Map<String, Object>> sourceRows = new MapListHandler().handle(sourceRs);
sourceRs.close();
st.close();
// load target table
st = conn.createStatement();
ResultSet targetRs = st.executeQuery("SELECT * FROM target");
List<Map<String, Object>> targetRows = new MapListHandler().handle(targetRs);
targetRs.close();
st.close();
// for every row in source, look for no match in target
List<Map<String, Object>> diffRows =
sourceRows.stream()
.filter(sourceRow -> rowExistsInTable(sourceRow, targetRows) == false)
.collect(Collectors.toList());
diffRows.stream().forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
}
EDIT:
you will notice that the filtering of sourceRows is now done according to result of method rowExistsInTable(). I added methods to search row in table and check rows' equality without relying on java 8 lambda syntax (also added as much documentation as I could :))
/**
* checks if {#code searchRow} exists in {#code table}
* existence is determined according to {#code areRowsEqual} method
* #param searchRow {#code Map<String, Object>} where keys are column names and values are column vales
* #param table {#code List} of {#code Map<String, Object>} rows
* #return {#code true} if {#code searchRow} was found in {#code table}
*/
public static boolean rowExistsInTable(Map<String, Object> searchRow, List<Map<String, Object>> table)
{
for (Map<String, Object> tableRow : table) {
if (areRowsEqual(tableRow, searchRow)) return true;
}
return false;
}
/**
* checks if all of row1 columns are found with same values in row2
* note: does not check if there is column in row2 that does not exist in row1
* #param row1
* #param row2
* #return {#code true} if {#code row1} is equal to {#code row2}
*/
public static boolean areRowsEqual(Map<String, Object> row1, Map<String, Object> row2)
{
// loop on row1 columns
for (Map.Entry<String, Object> row1Column : row1.entrySet()) {
String row1ColumnName = row1Column.getKey();
Object row1ColumnValue = row1Column.getValue();
// search row1 column in row2
if (row2.containsKey(row1ColumnName) &&
row2.get(row1ColumnName) != null &&
row2.get(row1ColumnName).equals(row1ColumnValue)) {
// row1 column was found in row2, nothing to do
} else {
// row1 column was not found in row2
return false;
}
}
return true; // all row 1 columns found in row 2
}
Related
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".
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.
Folks,
We have one requirement where we want to merge two excel sheets in to one workbook using JAVA.
We know this can be done with Apache POI.
But we donot want to do following. We just want to merge these two excel files in to single workbook.
Donot do : Load both Excel file in to memory. Their contents are huge more than 100k rows.
Thanks.
You can't just copy sheet to another workbook. You need to create you a new workbook, then create a sheet and add cell by cell the content of your sheets.
I can help you with 2 methods to copy row, and copy cell and depending method:
/**
* Copy row with style and merged region. This manage a shift in copy. You can copy row 1 to 10 and paste it between. this method can be use for copying in same sheet
* 21 and 30
* #param pSrcSheet source sheet
* #param pDestSheet dest sheet
* #param pSrcLine line to copy
* #param pDestLine line to paste
* #param pStyleMap just get a new HashMap<Integer, CellStyle> pStyleMap
* #param pLineShift the shift set 0 if you don't need to shift your row. Example copy row 1 to 10 and paste it between 21 and 30 you
* need set thhe shift value 20. The value could be negative to pick up the data
*/
public static void copyRow(Sheet pSrcSheet, Sheet pDestSheet, Row pSrcLine, Row pDestLine,
Map<Integer, CellStyle> pStyleMap, int pLineShift)
{
ArrayList<CellRangeAddress> mergedRegions = getMergedRegions(pDestSheet);
pDestLine.setHeight(pSrcLine.getHeight());
for (int j = pSrcLine.getFirstCellNum(); j < pSrcLine.getLastCellNum(); j++)
{
Cell oldCell = null;
Cell newCell = null;
// if no cell in row skip the iteration
if (j >= 0)
{
oldCell = pSrcLine.getCell(j);
newCell = pDestLine.getCell(j, Row.CREATE_NULL_AS_BLANK);
}
if (oldCell != null)
{
if (newCell == null)
{
newCell = pDestLine.createCell(j);
}
copyCell(oldCell, newCell, pStyleMap);
CellRangeAddress mergedRegion =
getCurrentMergedRegion(pSrcSheet, pSrcLine.getRowNum(), (short) oldCell.getColumnIndex());
if (mergedRegion != null)
{
CellRangeAddress newMergedRegion =
new CellRangeAddress(mergedRegion.getFirstRow() + pLineShift, mergedRegion.getLastRow()
+ pLineShift, mergedRegion.getFirstColumn(), mergedRegion.getLastColumn());
if (isNewMergedRegion(newMergedRegion, mergedRegions))
{
mergedRegions.add(newMergedRegion);
pDestSheet.addMergedRegion(newMergedRegion);
}
}
}
}
}
/**
* Copy cell with style from same workbook or not
* #param pOldCell
* #param pNewCell
* #param pStyleMap
*/
public static void copyCell(Cell pOldCell, Cell pNewCell, Map<Integer, CellStyle> pStyleMap)
{
if (pStyleMap != null)
{
if (pOldCell.getSheet().getWorkbook() == pNewCell.getSheet().getWorkbook())
{
pNewCell.setCellStyle(pOldCell.getCellStyle());
}
else
{
int stHashCode = pOldCell.getCellStyle().hashCode();
CellStyle newCellStyle = pStyleMap.get(stHashCode);
if (newCellStyle == null)
{
newCellStyle = pNewCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(pOldCell.getCellStyle());
pStyleMap.put(stHashCode, newCellStyle);
}
pNewCell.setCellStyle(newCellStyle);
}
}
switch (pOldCell.getCellType())
{
case Cell.CELL_TYPE_STRING:
pNewCell.setCellValue(pOldCell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
pNewCell.setCellValue(pOldCell.getNumericCellValue());
break;
case Cell.CELL_TYPE_BLANK:
pNewCell.setCellType(Cell.CELL_TYPE_BLANK);
break;
case Cell.CELL_TYPE_BOOLEAN:
pNewCell.setCellValue(pOldCell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
pNewCell.setCellErrorValue(pOldCell.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
pNewCell.setCellFormula(pOldCell.getCellFormula());
break;
default:
break;
}
}
/**
* return the cellRangeAdress of the merge region where the cell is. Null if the cell is not in merged region
* #param pSheet
* #param pRowNum
* #param pCellNum
* #return return the cellRangeAdress of the merge region where the cell is. Null if the cell is not in merged
* region
*/
public static CellRangeAddress getCurrentMergedRegion(Sheet pSheet, int pRowNum, int pCellNum)
{
for (int i = 0; i < pSheet.getNumMergedRegions(); i++)
{
CellRangeAddress merged = pSheet.getMergedRegion(i);
if (merged.isInRange(pRowNum, pCellNum))
{
return merged;
}
}
return null;
}
/**
* return the index of the merge region where the cell is. -1 if the cell is not in merged region
* #param pSheet
* #param pRowNum
* #param pCellNum
* #return return the index of the merge region where the cell is. -1 if the cell is not in merged region
*/
public static int getCurrentMergedRegionIndex(Sheet pSheet, int pRowNum, int pCellNum)
{
for (int i = 0; i < pSheet.getNumMergedRegions(); i++)
{
CellRangeAddress merged = pSheet.getMergedRegion(i);
if (merged.isInRange(pRowNum, pCellNum))
{
return i;
}
}
return -1;
}
/**
* return the cellRangeAdress of the merge region where the cell is. Null if the cell is not in merged region
* #param pSheet
* #param pRowNum
* #param pCellNum
* #return return the cellRangeAdress of the merge region where the cell is. Null if the cell is not in merged
* region
*/
public static ArrayList<CellRangeAddress> getMergedRegions(Sheet pSheet)
{
ArrayList<CellRangeAddress> mergedRegions = new ArrayList<CellRangeAddress>();
for (int i = 0; i < pSheet.getNumMergedRegions(); i++)
{
mergedRegions.add(pSheet.getMergedRegion(i));
}
return mergedRegions;
}
/**
* verify all boolean are true
* #param pValues
* #return
*/
public static boolean areAllTrue(boolean... pValues)
{
for (int i = 0; i < pValues.length; ++i)
{
if (pValues[i] != true)
{
return false;
}
}
return true;
}
/**
* Compare 2 region if they are the same return true
* #param pRegion region compare to pRegion2
* #param pRegion2 region compare to pRegion
* #return true if the region are the same, false if region are different
*/
public static boolean cellRangeAdressEquals(CellRangeAddress pRegion, CellRangeAddress pRegion2)
{
boolean r1 = (pRegion.getFirstRow() == pRegion2.getFirstRow());
boolean r2 = (pRegion.getLastRow() == pRegion2.getLastRow());
boolean c1 = (pRegion.getFirstColumn() == pRegion2.getFirstColumn());
boolean c2 = (pRegion.getLastColumn() == pRegion2.getLastColumn());
return areAllTrue(r1, r2, c1, c2);
}
/**
* Verify the it's a new region or existing
* #param pNewMergedRegion
* #param pMergedRegions
* #return
*/
public static boolean isNewMergedRegion(CellRangeAddress pNewMergedRegion,
ArrayList<CellRangeAddress> pMergedRegions)
{
boolean isNew = true;
int i = 0;
// we want to check if newMergedRegion is contained inside our collection
while (pMergedRegions != null && i < pMergedRegions.size() && isNew)
{
if (cellRangeAdressEquals(pMergedRegions.get(i), pNewMergedRegion))
{
isNew = false;
}
i++;
}
return isNew;
}
you can find some help on this thread : http://www.coderanch.com/t/420958/open-source/Copying-sheet-excel-file-excel
If you have more information about your problem, I will help you as i can ;)
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));
}
}
I built a function in java that searches in the database for 2 values and if they exist return the values;
public List<Conniction> findPath(int one,int two){
List<Conniction> list = new ArrayList<Conniction>();
Connection c = null;
String sql = "SELECT * FROM conniction WHERE oneid="+one+"&& twoid="+two;
try {
c = ConnectionHelper.getConnection();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int columncount = metaData.getColumnCount();
//direct result
if (columncount > 0) {
System.out.println("Match one and two found!");
while (rs.next()) {
list.add(processRow(rs));
}
}
else{
String sql2 = "SELECT * FROM conniction WHERE oneid="+one;
s = c.createStatement();
rs = s.executeQuery(sql2);
metaData = rs.getMetaData();
columncount = metaData.getColumnCount();
if (columncount > 0) {
System.out.println("One Match found!");
while (rs.next()) {
list.add(processRow(rs));
}
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
How do I check what the values of the parameters that are returned are, to check if its really the right answer for oneid and twoid. It always returns something different from what I have sent.
I don't know if that is the best solution, but you could:
* give the list object with parameters
* and then return a code
* check the code and use the list
your method gets the list as a parameter:
public int findPath(List<Conniction> list, int one, int two) {
...
if (columncount > 0) {
System.out.println("Match one and two found!");
while (rs.next()) {
list.add(processRow(rs));
}
return 2;
} else {
String sql2 = "SELECT * FROM conniction WHERE oneid="+one;
s = c.createStatement();
rs = s.executeQuery(sql2);
metaData = rs.getMetaData();
columncount = metaData.getColumnCount();
if (columncount > 0) {
System.out.println("One Match found!");
while (rs.next()) {
list.add(processRow(rs));
}
return 1;
}
}
...
}
in your code, where you call the method you check the return:
...
List<Conniction> connlist = new ArrayList<Conniction>();
int foo = findPath(connlist , one, two);
if (foo == 1) {
/*One Match found!*/
// do something with your connlist-Object;
} else if (foo == 2) {
/*Match one and two found!*/
// do something with your connlist-Object;
}
Your code has two serious problems that prevent it from working:
metaData.getColumnCount() (unsurprisingly) returns the number of columns, not the number of rows. The number of columns returned is a constant depending on what is selected in the query. In this case, you select *, so metaData.getColumnCount() will be exactly the number of columns in the conniction table. You don't know how many rows are in the rowset until you process it
You probably want or logic, not and, ie
"SELECT * FROM conniction WHERE oneid="+one+" OR twoid="+two