Resultset exhausted - java

Showing ResultSet exhausted on second time i call this method . First time no error. Showing error at obj[i][j] = rs.getString(1);
public static void createTableModel(ResultSet rs) {
try {
rs.first();
while(rs.next()) {
count++;
}
String [][] obj;
obj = new String [count][3];
rs.first();
for (int i=0; i<count; i++) {
for (int j=0; j < 3; j++) {
if(j == 0) {
obj[i][j] = rs.getString(1);
}
else if(j == 1) {
obj[i][j] = Integer.toString(rs.getInt(2));
}
else if(j == 2) {
obj[i][j] = rs.getString(6);
}
}
rs.next();
}
GlobalVariables.table1 = new DefaultTableModel(obj,
new String [] {
"Name", "Age", "License No"
}
);
}
catch (Exception e) {
e.printStackTrace();
}
}

I converted resultset to an list>
List<ArrayList<String>> result = new ArrayList<>();
do{
ArrayList<String> row = new ArrayList<>(6);
int i = 1;
while (i <= 6) {
row.add(GlobalVariables.data3.getString(i++));
}
result.add(row);
}while (GlobalVariables.data3.next());
It solved the problem. I still don't know why it showed the error exhausted resultset.

Related

Save a Resultset to an Array in java

I want to save the result of a whole Mysql table in an array
String sDriver = "com.mysql.jdbc.Driver";
String sURL = "jdbc:mysql://www.odorxd.xyz:3306/u218933149_odor_base";
try {
Class.forName(sDriver).newInstance();
Connection con = DriverManager.getConnection(sURL, "u218933149_estenoesodor", "Tsunayoshi27?");
PreparedStatement stmt = null;
ResultSet rs = null;
stmt = con.prepareStatement("SELECT * FROM justname");
rs = stmt.executeQuery();
while (rs.next()) {
for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
System.out.print(rs.getString(x) + "\t");
}
System.out.println("");
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
it returns this to me from the database
run:
brandon
Brandon
Julio
Daniel
BUILD SUCCESSFUL (total time: 1 second)
I want to save what is in the database in an array to be able to implement it with a sort and search method
String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan", "Brandon", "Brandon Jesus", "Brandon Flores", "Brandon Flores Flores"};
String temp;
System.out.println("Strings in sorted order:");
for (int j = 0; j < str.length; j++) {
for (int i = j + 1; i < str.length; i++) {
// comparing adjacent strings
if (str[i].compareTo(str[j]) < 0) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
System.out.println(str[j]);
}
that's why I need to save it in an array
I would appreciate any criticism or help as you do not have an idea, thank you
You can use a List.
List<String> list = new ArrayList<>();
while (rs.next()) {
for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
String str = rs.getString(x)
list.add(str);
System.out.print(str + "\t");
}
System.out.println();
}
String[] arr = list.toArray(new String[0]);
String temp;
// ... sort

how to return string value out of for loop scope

I am facing a issue when fatch the value from xl after that print under the for loop scope then printed. when declare the in return statement and call the method only first cell value print. I want 8 cell value.
public String Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row =0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath,"Course 7");
} catch (IOException e) {
e.printStackTrace();
}
for (Row = 20; Row<28; Row++) {
try {
s = XLUtils.getCellData(excelPath,"Course 7", Row,1);
return s;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("sss="+s);
}
return s;
}
You can use if(condition) to break/return the required value. For ex, I have a for loop interating upto 10. At value 6 I want to stop and return the value. It can be done as:
private test() {
for (int i = 10; i > 10; i++) {
if(i==5) {
return i;
}
}
}
If you want all the 8 cell values then you will have to hold those values in a list/array. You can do it as:
public List<String> Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row = 0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath, "Course 7");
} catch (IOException e) {
e.printStackTrace();
}
List<String> items = new ArrayList<String>();
for (Row = 20; Row < 28; Row++) {
try {
s = XLUtils.getCellData(excelPath, "Course 7", Row, 1);
items.add(s);
return s;
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("sss="+s);
}
return items;
}

Iterate vector element object

I am a newbie coder.
Can anyone teach me how to get the value inside storedVector1[3] ? I tried a lot of ways but i can only loop through storedVector and not the value inside the storedVector object
EDIT:
tableData.java
public class TableData {
static Vector storedVector = new Vector();
public void fillSortedData(File file, Vector data){
Workbook workbook = null;
Calendar now = Calendar.getInstance();
int monthnow = now.get(Calendar.MONTH) + 1;
try {
try {
workbook = Workbook.getWorkbook(file);
} catch (IOException ex) {
Logger.getLogger(
excelTojTable.class.getName()).log(Level.SEVERE, null, ex);
}
Sheet sheet = workbook.getSheet(0);
headers.clear();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell1 = sheet.getCell(i, 0);
headers.add(cell1.getContents()); }
data.clear();
for (int j = 1; j < sheet.getRows(); j++) {
Vector d = new Vector();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell = sheet.getCell(i, j);
d.add(cell.getContents());
CellType type = cell.getType();
if(type == CellType.DATE){
String cellDateStr = cell.getContents();
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
try {
Date cellDate = formatter.parse(cellDateStr);
int month = cellDate.getMonth() + 1;
if(monthnow != month) {
d.clear();
//d.removeAllElemen8ts();
i = sheet.getColumns();
}
} catch (ParseException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
if(d.isEmpty() == false) {
d.add("\n");
data.add(d);
storedVector.add(d);
}
}
} catch (BiffException e) {
e.printStackTrace();
}
}
public void emailList() {
int abc = storedVector.size();
//iterate through the vector and get all the element
}
}
}
I created a vector "data" using the same method as storedVector in another java class.
In tableData.java, I wanted to create a method "emaillist" that can iterate and get all the email that was show in the picture and save it in a list or array
Vector extends AbstractList. So it should have a Vector.get(i) method.
Try using
Vector v = storedVector.get(1);
Object o = v.get(3);
if storedVector is a list/set of Vector, this code can help:
for(Vector vector: storedVector){
for(int i=0; i< vector.size(); i++){
//access to vector[i]
}
}

J2ME , Quizz using choiceGroups

I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}

Compile time error on online compilation?

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class database {
String fileName;
Scanner input;
String[][] data;
List<String> useful_list;
List<String> records;
ArrayList<Object> handles;
public database(String fileName) {
this.fileName = fileName;
}
public void openFile() {
try {
input = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return;
}
}
public void readRecords() {
// Read all lines (records) from the file into an ArrayList
records = new ArrayList<String>();
try {
while (input.hasNext())
records.add(input.nextLine());
} catch (Exception e) {
// TODO: handle exception
}
}
public void parseFields() {
String delimiter = ",\n";
// Create two-dimensional array to hold data (see Deitel, p 313-315)
int rows = records.size(); // #rows for array = #lines in file
data = new String[rows][]; // create the rows for the array
int row = 0;
for (String record : records) {
StringTokenizer tokens = new StringTokenizer(record, delimiter);
int cols = tokens.countTokens();
data[row] = new String[cols]; // create columns for current row
int col = 0;
while (tokens.hasMoreTokens()) {
data[row][col] = tokens.nextToken().trim();
col++;
}
row++;
}
}
public static void main(String[] args) {
String filename = null;
String[] values = new String[4];
String input = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
try {
filename = reader.readLine();
input = reader.readLine();
values = input.split(",");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Invalid Input");
return;
}
int[] input1;
input1 = new int[4];
try {
for (int j = 0; j < values.length; j++) {
input1[j] = Integer.parseInt(values[j]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Invalid Input");
return;
}
if (input1[0] >= 4 || input1[0] <= 0) {
System.out.println("Invalid Input");
return;
}
database file1 = new database(filename);
file1.openFile();
file1.readRecords();
file1.parseFields();
file1.search(input1[1]);
if (file1.useful_list.size() == 0) {
System.out.println("Data Unavailable");
return;
}
file1.sortarray(input1[0] - 1);
int width = input1[2];
int skip = (input1[3] - 1) * width;
Iterator<Object> it = file1.handles.iterator();
for (int i = 1; i <= skip; i++) {
if (it.hasNext()) {
it.next();
} else {
System.out.println("Data Unavailable");
return;
}
}
for (int j = 1; j <= width && it.hasNext(); j++) {
String[] a = (String[]) it.next();
for (int i = 0; i < a.length; i++)
if(i<a.length-1)
System.out.print(a[i] + ",");
else
System.out.print(a[i]);
System.out.println();
}
}
void sortarray(final int index) {
handles = new ArrayList<Object>();
for (int i = 0; i < data.length; i++)
handles.add(data[i]);
Collections.sort(handles, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
String[] a = (String[]) o1;
String[] b = (String[]) o2;
if (index == 1 || index == 0) {
int left = Integer.parseInt(a[index]);
int right = Integer.parseInt(b[index]);
return Integer.compare(left, right); //Line 165
} else {
if (a.length == 0 && b.length == 0)
return 0;
if (a.length == 0 && b.length != 0)
return 1;
if (a.length != 0 && b.length == 0)
return -1;
return a[index].compareTo(b[index]);
}
}
public boolean equals(Object o) {
return this == o;
}
});
}
void search(int searchs) {
useful_list = new ArrayList<String>();
for (int row = 0; row < data.length; row++) {
if (Integer.parseInt(data[row][0]) == searchs) {
// store in array list
useful_list.add(data[row][0] + "," + data[row][1] + ","
+ data[row][2] + "," + data[row][3]);
}
}
if (useful_list.size() == 0) {
return;
}
String delimiter = ",\n";
// Create two-dimensional array to hold data (see Deitel, p 313-315)
int rows = useful_list.size(); // #rows for array = #lines in file
data = new String[rows][]; // create the rows for the array
int row1 = 0;
for (String record : useful_list) {
StringTokenizer tokens = new StringTokenizer(record, delimiter);
int cols = tokens.countTokens();
data[row1] = new String[cols]; // create columns for current row
int col1 = 0;
while (tokens.hasMoreTokens()) {
data[row1][col1] = tokens.nextToken().trim();
col1++;
}
row1++;
}
}
}
this code is working fine on eclipse .
but if i submit it for my online compilation ..
it shows compile time error.
error message
*database.java 163 cannotfindsymbolsymbol methodcompare int int location class java.lang.Integer return Integer.compare left right ;^1error*
Integer.compare was introduced to Java in version 1.7. Chances are that the online compiler has an earlier version of the compiler
Integer.compare(int,int) was introduced in Java 1.7. I expect you are seeing that error because Java 6 or earlier is used to compile the code. The docs. themselves (linked above) show how to do it for earlier Java (you should consult them at times like this).
Integer.valueOf(x).compareTo(Integer.valueOf(y))

Categories