Retrieving values column wise from database using jdbc - java

I want to retrieve data from database column wise. Say if I have Column 'a' then I want all values of that column and then I have another column say 'b' then I want to get all values of that column and so on for all columns.
My code is giving me row wise value. First it will retrieve data from first row and then second and so on. My code is as follows.
while (rs.next()) {
for(inti=1;i<=rsMetaData.getColumnCount();i++) {
System.out.println(rs.getString(i));
}
}
Please suggest how to get all values of first column then second and so on.

Iterate Data Row wise and convert to Column wise. Something Like this :
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM table");
ResultSetMetaData rsMetaData = rs.getMetaData();
Map<String, List<Object>> resultMap = new LinkedHashMap<>();
while (rs.next()) {
for(int i=1;i<=rsMetaData.getColumnCount();i++) {
String strColumnName = rsMetaData.getColumnName(i);
Object columnValue = rs.getObject(i);
if(resultMap.containsKey(strColumnName)){
resultMap.get(strColumnName).add(columnValue);
}else{
List<Object> resultList = new ArrayList<>();
resultList.add(columnValue);
resultMap.put(strColumnName,resultList);
}
}
}
// Iterate Data Column Wise
for(Iterator<Map.Entry<String, List<Object>>> iterator = resultMap.entrySet().iterator();iterator.hasNext();){
Map.Entry<String, List<Object>> entry = iterator.next();
System.out.println("Column Name: "+entry.getKey());
System.out.println("Column Values: "+entry.getValue());
}

A more flexible solution might use a HashMap instead of a List. This way you can store the column names as keys, which makes retrieving values easier and more transparent.
//declare a HashMap
Map<String,Object> hMap = new HashMap<String,Object>();
public void populateColumns(ResultSet rs) {
try{
while(rs.next()){
for (int i=1;i<=rs.getMetaData().getColumnCount();i++) {
Object obj=rs.getObject(i); //get the value for whatever column the result has
hMap.put(rs.getMetaData().getColumnName(i), obj);
} }
}catch (Exception e) {
//handle the exception
}
}
Note that if you want special handling for some database types /Java types, you can use the instanceof operator.
for (int i=1;i<=rs.getMetaData().getColumnCount();i++) {
Object obj=rs.getObject(i); /
if(obj instanceof String) //if obj is a String
hMap.put(rs.getMetaData().getColumnName(i), new String(((String)obj).getBytes("UTF-8"),"UTF-8"));
else //for every other objects
hMap.put(rs.getMetaData().getColumnName(i), obj);
UPDATE:
To get the output like you want try this
public void populateColumns(ResultSet rs) {
List<Object> list = new ArrayList<Object>();
int colCount;
try{
while(rs.next()){
colCount = rs.getMetaData().getColumnCount();
for (int i=1;i<=colCount;i++) {
Object obj=rs.getObject(i); //get the value for whatever column the result has
list.add(obj);
}
}
}catch (Exception e) {
//handle the exception
}
//
List<Object> sortedByCol = new ArrayList<Object>();
for(int j=0; j<colCount;j++){
for(int i=j; i<list.size(); i+=colCount){
sortedByCol.add(list.get(i));
}
}
For input like
col a col b col c
1 row 1 2 3
2 row 1 2 3
your output list (sortedByCol) will have
1, 1, 2, 2, 3, 3

have comma delimitered String value for each column which is in an ArraList
Something like (Sorry not in front of a computer)
ArrayList<String> columnValList = new ArrayList<>();
while (rs.next()) {
for(inti=0;i<rsMetaData.getColumnCount();i++) {
// get element for this col - create if doesnt exist
String cols = columnValList.get (i); // error checking needed
cols = cols + "," + rs.getString (i + 1);
// put it back
columnValList.set (i, cols);
}
}
after this you will have element(0) containing all values for the first columns etc

Related

Java, MySQL method for returning ambiguous ResultSet as an ArrayList

I'm working on an assignment but am confused by the wording of this task:
"Add a method named getData that accepts an SQLstring and the number of fields.
getData should perform the query that was passed in, then convert the ResultSet into a simple 2-d ArrayList."
Here is what I have so far...
public ArrayList<ArrayList<String>> getData(String sqlString, int numFields){
Statement stmnt= this.conn.createStatement();
ResultSet rs = stmnt.executeQuery(sqlString);
ArrayList<ArrayList<String>> ary = new ArrayList();
int row = 0;
while (rs.next()){ // Get next row
for (int i = 1; i <= numFields; i++) { // each column
ary[row][i-1] = rs.getString(i);
}
row++;
}
return ary;
}
I'm getting an error error: array required, but ArrayList<ArrayList<String>> found
ary[row][i-1] = rs.getString(i);
^
Thank you in advance for your help and for reading.
EDIT: I believe this is the final/correct/working version, thanks to the answers provided by other awesome users :) now jGrasp is just yelling at me about catching exceptions. I appreciate the help!!!
public ArrayList<ArrayList<String>> getData(String sqlString, int numFields){
Statement stmnt= this.conn.createStatement();
ResultSet rs = stmnt.executeQuery(sqlString);
ArrayList<ArrayList<String>> ary = new ArrayList<>();
while (rs.next()){ // Get next row
ArrayList<String> columnsList = new ArrayList<>();
for (int i = 1; i <= numFields; i++) { // each column
columnsList.add(rs.getString(i));
// Add the list of columns to our list of rows
ary.add(columnsList);
}
}
return ary;
}
You need to use the get() method to get the element at a particular index from an ArrayList. You can't use [] to get the element at a particular index, in an arraylist. Its possible only for arrays and your resultSet is not an array, but an ArrayList.
You can add to arraylist instead of array as below,
ArrayList<ArrayList<String>> ary = new ArrayList();
int row = 0;
while (rs.next()){ // Get next row
ArrayList<String> columns = new ArrayList<>();
for (int i = 1; i <= numFields; i++) { // each column
columns.add(rs.getString(i));
}
ary.add(columns)
}
And thet use get() method on list to retrieve.
You can think of a 2D ArrayList as being a "list of lists." So as Kartik mentioned in the comments, you would declare it like this:
ArrayList<ArrayList<String>> rows = new ArrayList<>();
Now that you have your base List, you can create and add new ones to that base list:
while (rs.next()){ // Get next row
ArrayList<String> columnsList = new ArrayList<>();
for (int i = 1; i <= numFields; i++) { // each column
columnsList.add(rs.getString(i));
// Add the list of columns to our list of rows
rows.add(columnsList);
}
}
return rows;
You can do this trivially using Apache DbUtils:
public ArrayList<ArrayList<String>> getData(String sqlString, int numFields){ // numFields unnecessary
QueryRunner run = new QueryRunner();
List ret = new ArrayList();
ret.addAll(run.query(conn, sqlString));
DbUtils.close(conn);
return ret;
}

Excel reading data from table 1 and write the calculated data into table2

I have two tables from the same excel in a different sheets. In table 1: There are two columns like "Actual value" and "Saved Value" The cell values of two columns are looks like this Actual value : row(0)2005.99, row(1)6774.00... Saved value : row(0)ClaimsTotal, row(1)ClaimsAServiceTotal
In table 2: There is an column name called "Calculations" "Value1" "Value2" "Value3" The cell values of Calculations column looks like this Calculations: row(0)ClaimsTotal + ClaimsAServiceTotal = ClaimsGrandTotal ......etc
I have written the code for excel reading and writing, below are the methods for the reference
ExcelReader excelutil = new ExcelReader("Guardian Role");
Object[] savedValue = excelutil.readExcelByColName("Saved Value");
Object[] actualValue = excelutil.readExcelByColName("Actual Value");
ExcelReader readCaliTable = new ExcelReader("Data Verification");
Object[] caliculation = readCaliTable.readExcelByColName("Calculations");
My requirement is: First I need to split table 2 Calculations column cell value and need to keep in two different strings like value[0] = ClaimsTotal and value1=ClaimsAServiceTotal. based on this cell string I want to check this in table 1 Saved Value column, If it is present then corresponding value from table 1 Actual Value column need to get and do calculation Ex:
ClaimsTotal = 2005.99 (I need to print this in table 2 value 1)
ClaimsAServiceTotal= 6774.00 (I need to print this in table 2 value 2)
(2005.99+6774.00)= total (I need to print this in table 2 value 3) like wise in some rows there will be +,=
public ExcelReader(String sheetname, String sheetname1) throws IOException {
super();
this.filename = configProps.getProperty("testData");;
this.sheetname = sheetname;
this.sheetname1 = sheetname1;
this.excelFile = new FileInputStream(new File(this.filename));
this.workbook = new XSSFWorkbook(this.excelFile);
this.sheet = workbook.getSheet(this.sheetname);
this.sheet1 = workbook.getSheet(this.sheetname1);
}
public void verifyData(String colName) throws FileNotFoundException {
Object[] calc = this.readExcelByColName(colName);
for (int i = 0; i < calc.length; i++) {
String string = (String) calc[i];
string = string.replaceAll("\\s", "");
String[] parts = string.split("(\\+)|(\\=)");
int j = 1;
for (String s : parts) {
int[] index1 = findIndex(this.sheet1, s);
int[] index2 = findIndex(this.sheet, string);
this.sheet.getRow(index2[0]).getCell((index2[1] + j))
.setCellValue(this.sheet1.getRow(index1[0]).getCell(index1[1] - 1).getStringCellValue());
j++;
}
}
this.outFile = new FileOutputStream(new File(this.filename));
}
private int[] findIndex(Sheet sheet, String cellContent) {
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getStringCellValue().replaceAll("\\s", "").equals(cellContent)) {
int[] index = { row.getRowNum(), cell.getColumnIndex() };
return index;
}
}
}
}
return null;
}
main method#Test
ExcelReader excelUtil2 = new ExcelReader("Verify Data","Guardian Angel Hospice");
excelUtil2.verifyData("Calculations");
Object[] data2 = excelUtil2.readExcelByColName("Value1");
for (int i = 0; i < data2.length; i++) {
System.out.println(data2[i]);
}
excelUtil2.saveAndCloseExcel();
PFA Excel

retrieve values of rows (from Postgresql) in a list in java

I Used a HashMap for handling my ResultSet queried from PostgreSql using the code suggested by RHT
public List resultSetToArrayList(ResultSet rs) throws SQLException{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
ArrayList list = new ArrayList(50);
while (rs.next()){
HashMap row = new HashMap(columns);
for(int i=1; i<=columns; ++i){
row.put(md.getColumnName(i), rs.getObject(i));
}
list.add(row);
}
return list;
}
I did it beacuse I wanted to shuffle this collection afterwards.
now each row is like that:
{owner=22172613#N07, count=2}
I do not know how I can do a for/each loop that I retrieve each owner id and corresponding number !!
So you have an ArrayList each element of which is a HashMap that contains in its key the column names of the results and in its values the values of those columns.
A loop that will most probably help you is the following:
//call your method resultSetToArrayList here
List<Map> list = (List<Map>) resultSetToArrayList(rs);
//loop the list
for(Map r: list) {
System.out.println("row data: ");
final Iterator columnIterator = r.keySet().iterator();
while(columnIterator.hasNext()) {
final Object next = columnIterator.next();
System.out.println("\tColumn: " + next + " / Value: " + r.get(next));
}
}

How can I add rows and columns to a JavaFX 8 TableView

I see examples on the internet for adding a row to a TableView, for example using the Person class in the Oracle documentation.
But I have a variable number of columns, so I can't bind to a Person (or any other) bean business object.
The Oracle example goes on to show how to bind columns to property names, but for that, it only shows how to add columns, but not rows.
My question is, can someone point me to a Hello, World example of dynamically adding arbitrary columns and/or rows to a JavaFX 8 TableView?
Use a List<String> (for example) for the data type, and just set the cell value factory as a callback that indexes into the list.
For example, this will create a TableView<List<String>> that is constructed out of an arbitrary tab-delimited text file. Not all rows in the file need have the same number of elements (it will pad with blanks). (It doesn't support escaped tabs, etc):
public TableView<List<String>> readTabDelimitedFileIntoTable(Path file) throws IOException {
TableView<List<String>> table = new TableView<>();
Files.lines(file).map(line -> line.split("\t")).forEach(values -> {
// Add extra columns if necessary:
for (int i = table.getColumns().size(); i < values.length; i++) {
TableColumn<List<String>, String> col = new TableColumn<>("Column "+(i+1));
col.setMinWidth(80);
final int colIndex = i ;
col.setCellValueFactory(data -> {
List<String> rowValues = data.getValue();
String cellValue ;
if (colIndex < rowValues.size()) {
cellValue = rowValues.get(colIndex);
} else {
cellValue = "" ;
}
return new ReadOnlyStringWrapper(cellValue);
});
table.getColumns().add(col);
}
// add row:
table.getItems().add(Arrays.asList(values));
});
return table ;
}
Kind of clunky, but this sample code seems to work:
TableView table = new TableView<>();
private char nextChar = 'A';
private void addColumn(TableView table) {
String mapChar = String.valueOf(nextChar++);
TableColumn<Map, String> column = new TableColumn<>("Class " + mapChar);
column.setCellValueFactory(new MapValueFactory(mapChar));
column.setMinWidth(130);
column.setCellFactory(cellFactoryForMap);
table.getColumns().add(column);
}
private void addRow(TableView table) {
ObservableList<Map> allData = table.getItems();
int offset = allData.size();
Map<String, String> dataRow = new HashMap<>();
for (int j = 0; j < table.getColumns().size(); j++) {
String mapKey = Character.toString((char) ('A' + j));
String value1 = mapKey + (offset + 1);
dataRow.put(mapKey, value1);
}
allData.add(dataRow);
}
}

returning an arraylist of arraylist from a resultset in java

I created a database wrapper class in java and created a method called fetchAll(query).
this.openConnection();
ArrayList<String> results = new ArrayList<String>();
PreparedStatement stmt = this.conn.prepareStatement(query);
ResultSet resultset = stmt.executeQuery();
ResultSetMetaData metadata = resultset.getMetaData();
int numcols = metadata.getColumnCount();
while (resultset.next()) {
int i = 1;
while (i < numcols) {
results.add(resultset.getString(i++));
}
}
this.closeConnection();
return results;
Now it returns something like this:
[1, name1, address1, age1, 2, name2, address2, age2, 2, name2, address2, age3]
Which I found odd and the method does not return all columns, it lacks 1 column, why is it?
How can I achieve something like this
[
[1,name1,address1,age1,bday1],
[2,name2,address2,age2,bday2],
[3,name3,address3,age3,bday3]
]
Like this:
List<List<String>> result = new ArrayList<>(); // List of list, one per row
...
while (resultset.next()) {
List<String> row = new ArrayList<>(numcols); // new list per row
int i = 1;
while (i <= numcols) { // don't skip the last column, use <=
row.add(resultset.getString(i++));
}
result.add(row); // add it to the result
}
ResultSet resultset = statement.executeQuery(sql);//from DB
int numcols = resultset.getMetaData().getColumnCount();
List <List <String> > result = new ArrayList<>();
while (resultset.next()) {
List <String> row = new ArrayList<>(numcols); // new list per row
for (int i=1; i<= numcols; i++) { // don't skip the last column, use <=
row.add(resultset.getString(i));
System.out.print(resultset.getString(i) + "\t");
}
result.add(row); // add it to the result
System.out.print("\n");
}

Categories