I have a Result set returned using a query:
String query = "select Bookname, SubjectName from books join Subjects on Subjects.SubjectID = Books.subjectID where classID = '1a'";
ResultSet temp = null;
try
{
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
temp = rs;
}
I was just wondering is it possible to turn the Resultset into two seperate arrays: eg BookName[] and BookSubject[] so I can show them in a list view later on? Relatively new to resultset and this concept in android
You should be able to easily iterate through the results on the result set, populating each array with the results as you interate.
Something like this:
...
ResultSet rs = st.executeQuery(query);
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> subjects = new ArrayList<String>();
while (rs.next()) {
names.add(rs.getString(1));
subjects.add(rs.getString(2));
}
// finally turn the array lists into arrays - if really needed
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);
String[] subjectArr = new String[subjects.size()];
subjectArr = subjects.toArray(subjectArr);
Hope that helps!
Related
I have a resultset class that all of the query operations are stored. My problem is thatI am trying to fill a jtable with resultset data but I am only able to display the data in one column where I have three. This is the snippet of the resultset class:
public static List<List<String>> getAllFabrics() throws SQLException{
sql = "SELECT * FROM fabric";
List<List<String>> values = new ArrayList<>();
List<String> id = new ArrayList<>();
List<String> item = new ArrayList<>();
List<String> supplier = new ArrayList<>();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
//metaData = rs.getMetaData();
//int columnNum = metaData.getColumnCount();
while(rs.next()){
id.add(String.valueOf(rs.getInt("id")));
item.add(rs.getString("ItemDesc"));
supplier.add(rs.getString("Supplier"));
}
values.add(id);
values.add(item);
values.add(supplier);
return values;
}
and this is the jtable method that I am trying for hours to solve:
public static DefaultTableModel loadTable(){
ModelDB model = null;
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("ID");
tableModel.addColumn("Fabric");
tableModel.addColumn("Supplier");
try{
List<String> id = model.getAllFabrics().get(0);
List<String> item = model.getAllFabrics().get(1);
List<String> supplier = model.getAllFabrics().get(2);
//System.out.println(model.getAllFabrics().size()); tableModel.addRow(new Object[]{subRow});
for(List<String> row:model.getAllFabrics()){
tableModel.addRow(new Object[]{id,item,supplier});
}
}catch(SQLException ex){
ex.printStackTrace();
}
return tableModel;
}
I can't find a way to iterate the values to display in their respective column.
Original answer
You are almost there! You only need to change the loop:
for(int i = 0; i < id.size(); i++) {
tableModel.addRow(new Object[] {id.get(i),item.get(i),supplier.get(i)});
}
But as said in the comments, you should consider changing to an array of rows, not columns.
Edit
This is one approach. It is basically same as your code except the rows/columns are interchanged so the method returns a List of rows, not columns:
public static List<List<String>> getAllFabrics() throws SQLException{
sql = "SELECT * FROM fabric";
List<List<String>> values = new ArrayList<>();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
List<String> row = new ArrayList<>();
row.add(String.valueOf(rs.getInt("id")));
row.add(rs.getString("ItemDesc"));
row.add(rs.getString("Supplier"));
// Now row contains {id, item, supplier}
values.add(row);
}
return values;
}
Then in your loadTable() method change to:
...
try{
for(List<String> row: model.getAllFabrics()){
tableModel.addRow(row.toArray(new String[row.size()]);
}
...
In your original code you call model.getAllFabrics() multiple times to get the return value. This is not good because every time you do that the method gets called and it needs to make the SQL-request again etc. Store the return value in a variable instead. In this case though as the return value is only accessed once you can equally just do as I described above.
Hope this helps :)
ResultSet rs = dbmd.getSchemas();
while(rs.next()) {
String DbNames = rs.getString("TABLE_SCHEM");
}
I'm trying to store the value of DbNames and use it later. I tried using ArrayList
ResultSet rs = dbmd.getSchemas();
ArrayList<String> dbs = new ArrayList<>();
while(rs.next()) {
dbs.add(rs.getString("TABLE_SCHEM"));
}
for(String[] s : dbs)
{
System.out.println(Arrays.toString(s));
}
I'm new to programming and used StackOverflow resources to fix my problem, but I'm still having problems. Please help me figure this out.
Currently, your ArrayList is a raw type because you have not specified a data type for the ArrayList. Change your ArrayList declaration to a generic type by using
ArrayList<String> dbs = new ArrayList<>();
That way, when you try to access the values later, they will be String instead of Object.
Your new code will be
ResultSet rs = dbmd.getSchemas();
ArrayList<String> dbs = new ArrayList<>();
while(rs.next()) {
dbs.add(rs.getString("TABLE_SCHEM"));
}
for(String s : dbs) {
System.out.println(s);
}
Create ArrayList to save your data retrieved from the result set as below:
ResultSet resultset = ;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
arrayList.add(resultset.getString('TABLE_SCHEM'));
}
I am trying to get the values from the database using servlet and it retrieving fine inside the while loop only i can accessing the values retrieved from the database but i need to consolidatre all values into a single object. here is my code,
String moduleId = request.getParameter("moduleId").trim();
String temp[] = moduleId.split("/");
for(String s:temp){
String modId[]=s.split("/");
PreparedStatement ps = null;
Connection connection=DatabaseConnection.getConnection();
ps=connection.prepareStatement("select * from testcase_sahi where module_id=?");
ps.setString(1,modId[0]);
ResultSet rs=ps.executeQuery();
while(rs.next()){
System.out.println(".............TC ID...."+rs.getString("testcase_id"));
System.out.println(".............TC Name...."+rs.getString("testcase_name"));
testCase=rs.getString("testcase_name");
/*fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
System.out.println("****"+out.TC_OBJECT);
out.writeObject(testCase);
out.close();*/
}
you can simply store your data in a List...
String moduleId = request.getParameter("moduleId").trim();
String temp[] = moduleId.split("/");
for(String s:temp){
String modId[]=s.split("/");
PreparedStatement ps = null;
Connection connection=DatabaseConnection.getConnection();
ps=connection.prepareStatement("select * from testcase_sahi where module_id=?");
ps.setString(1,modId[0]);
ResultSet rs=ps.executeQuery();
List temporaryList = new ArrayList(); //HERE
while(rs.next()){
System.out.println(".............TC ID...."+rs.getString("testcase_id"));
System.out.println(".............TC Name...."+rs.getString("testcase_name"));
testCase=rs.getString("testcase_name");
temporaryList.add(testCase); //HERE
}
serializeData(temporaryList) //and HERE
}
Here is the original code which has defined String-Array (25). It is working perfectly. But I don't need to define it as 25. Instead, I used arraylist. Please check my code.
Using String of array:
public String[] getemailAddr(String strAccountnbr) throws Exception {
String strQuery2 = null;
ResultSet rs = null;
PreparedStatement ps = null;
String[] emailAddress = new String[25];
int i=0;
strQuery2 = "SELECT c.EmailAddress AS EmailAddress" +
" FROM customeremailid c " +
"WHERE c.AccountNbr = ? " ;
logMsg("strQuery2: "+strQuery2);
ps = getDBConn().prepareStatement(strQuery2);
ps.setString(1, strAccountnbr);
rs = ps.executeQuery();
while(rs.next())
{
emailAddress[i]=(rs.getString("EmailAddress"));
logMsg("emailAddress[i]"+" "+i+": "+emailAddress[i]);
i=i+1;
}
return emailAddress;
}
Here, I need to change String-Array to Arraylist. I tried something like this,
public String[] getemailAddr(String strAccountnbr) throws Exception {
String strQuery2 = null;
ResultSet rs = null;
PreparedStatement ps = null;
//Newly tried //
ArrayList<String> strArrEmailIds = new ArrayList<String>();
String[] emailAddress= new String[strArrEmailIds.size()];
strArrEmailIds.toArray(emailAddress);
//Newly tried //
int i=0;
strQuery2 = "SELECT c.EmailAddress AS EmailAddress" +
" FROM customeremailid c " +
"WHERE c.AccountNbr = ? " ;
logMsg("strQuery2: "+strQuery2);
ps = getDBConn().prepareStatement(strQuery2);
ps.setString(1, strAccountnbr);
rs = ps.executeQuery();
while(rs.next())
{
emailAddress[i]=(rs.getString("EmailAddress"));
logMsg("emailAddress[i]"+" "+i+": "+emailAddress[i]);
i=i+1;
}
return emailAddress;
}
Email ids are get from database instead of example.com.
But I am getting
java.lang.ArrayIndexOutOfBoundsException: 0 error
in this line.
emailAddress[i]=(rs.getString("EmailAddress"));
Please help!
This is not how you use an ArrayList.
First, you need to write:
List<String> strArrEmailIds = new ArrayList<>();
So, program to the interface and use the Java 7 diamond operator.
Next, remove the index i. You don't need this.
Finally, just do:
emailAddress.add(rs.getString("EmailAddress"));
To convert it back to an String[] you can then do:
String[] arr = emailAddress.toArray(new String[emailAddress.size()]);
Here is my suggestion for you final code:
public String[] getemailAddr(String strAccountnbr) throws Exception {
final List<String> emailAddress = new ArrayList<>();
final String strQuery2 = "SELECT c.EmailAddress AS EmailAddress"
+ " FROM customeremailid c "
+ "WHERE c.AccountNbr = ? ";
try (final PreparedStatement ps = getDBConn().prepareStatement(strQuery2)) {
ps.setString(1, strAccountnbr);
try (final ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
emailAddress.add(rs.getString("EmailAddress"));
}
}
}
return emailAddress.toArray(new String[emailAddress.size()]);
}
I have removed your pointless assignments to null. I have added try-with-resources blocks to close your external resources, you code was one massive memory leak.
If you have a ArrayList, then you dont need a array again, indeed a ArrayList is backed by Array itself and its dynamic in size.
List<String> emailAddress= new ArrayList<String>(); // dynamic array
...
while(rs.next()){
emailAddress.add((rs.getString("EmailAddress"));
...
}
return emailAddress.toArray(new String[emailAddress.size()]); // creating array of String type
And ArrayList#toArray converts List to Array which has done at last in the code.
declare it as
ArrayList<String> emailAddress= new ArrayList<String>();
...
emailAddress.add((rs.getString("EmailAddress"));
convert it to String[]:
return emailAddress.toArray(new String[emailAddress.size()]);
You use ArrayList here wrongly in your code. When you define
ArrayList<String> strArrEmailIds = new ArrayList<String>();
String[] emailAddress= new String[strArrEmailIds.size()];
strArrEmailIds.toArray(emailAddress);
strArrEmailIds by default has a size of 0, so the generated emailAddress array also gets a length of 0. Later in the while loop, you are trying to assign the value to the emailAddress[0], it will throw ArrayIndexOutOfBoundsException.
Instead, the correct way is :
ArrayList<String> strArrEmailIds = new ArrayList<String>();
//....
while(rs.next()){
//....
strArrEmailIds.add(rs.getString("EmailAddress"));
}
//....
String[] emailAddress = strArrEmailIds.toArray(new String[strArrEmailIds.size()]);
java.lang.ArrayIndexOutOfBoundsException: 0 if your result set goes beyond 25 itteration.
How to convert array to ArrayList ?
Arrays.asList(myArray)
in your case you can have a list and in the resulset itteration you can add them to the list like
List<String> emails = new ArrayList<String>();
while(...){
emails.add(rs.getString("EmailAddress"));
}
I want to convert my Resultset to List in my JSP page. and want to display all the values. This is my query:
SELECT userId, userName
FROM user;
I have executed that using preparedstatement and got the Resultset. But how to convert it as a List and want to display the result like this:
userID userName
------------------
1001 user-X
1006 user-Y
1007 user-Z
You need to iterate over the ResultSet object in a loop, row by row, to pull out each column value:
List ll = new LinkedList();
ResultSet rs = stmt.executeQuery("SELECT userid, username FROM USER");
// Fetch each row from the result set
while (rs.next()) {
int i = rs.getInt("userid");
String str = rs.getString("username");
//Assuming you have a user object
User user = new User(i, str);
ll.add(user);
}
You could always use Commons DbUtils and the MapListHandler. From the doc:
ResultSetHandler implementation that
converts a ResultSet into a List of
Maps
so it'll take a lot of boilerplate code out of your hands.
A ResultSet should never get as far as a JSP. It should be mapping into a data structure or object and closed inside the method scope in which it was created. It's a database cursor, a scarce resource. Your app will run out of them soon if you persist with such a design.
var rs = stmt.executeQuery();
List<Map<String, Object>> result = new ArrayList<>();
while (rs.next()) {
Map<String, Object> resMap = new HashMap<>();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
resMap.put(rs.getMetaData().getColumnName(i), rs.getObject(i));
}
result.add(resMap);
}
You can make a list of lists.
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
List row = null;
List table = new List();
while(rs.next())
{
for(int i = 0; i < n; i++)
row.add(rs.next(i);
tabla.add(row)
}