Storing values inside while loop using JDBC - java

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'));
}

Related

How to return list for the following type "List<List>" having an another object added to this list

I am learning JDBC concept where the problem has occurred while trying to return List. I cannot have Invoice list and the type has to be List. Kindly help me.The following error has occurred "The method add(List) in the type List<List> is not applicable for the arguments (Invoice)"
List<List> invoiceGroupByCustomer() throws SQLException {
List<List> list = new ArrayList<List>();
String query1 = "select customer_name,sum(total_amount),sum(balance) from invoice GROUP BY customer_name ORDER BY customer_name";
try
{
DbConnection obj = new DbConnection();
Connection con = obj.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query1);
while(rs.next())
{
Invoice invoiceobj = new Invoice();
invoiceobj.setCustomerName(rs.getString("customer_name"));
invoiceobj.setTotalAmount(rs.getDouble("sum(total_amount)"));
invoiceobj.setBalance(rs.getDouble("sum(balance)"));
list.add(invoiceobj);
}
}catch(Exception e)
{
e.printStackTrace();
}
return list;
}
List<List> list = new ArrayList<List>();
You have to put "List object" in every index of list because you have the list of lists.
Replace the line
list.add(invoiceobj);
with
list.add(Arrays.asList(invoiceobj));
Hope it will work.
Or You can can change the method return type from List<List> to List and return the same object.

Populate List<Object> from ResultSet without creating new Object for each dataset

I have been always using the following code to add Objects from a ResultSet into a List. However someone commented that it is not very efficient to create a new Object for every dataset in the ResultSet. Is there a better way? Or, is there a whole different way to add Object from a ResultSet to a List?
public static List<Students> selectFromDatabase(Connection conn, Statement stmt){
List<Students> list = new ArrayList<Students>();
String select = "SELECT * FROM students";
ResultSet rs = null;
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(select);
while(rs.next()){
//you have to create a new OBJECT FOR EACH LOOP
Students student = new Students();
student.setStudentId(rs.getInt(1));
student.setName(rs.getString(2));
student.setGpa(rs.getInt(3));
list.add(student);
}
}catch(SQLException e){
System.out.println(e.getMessage());
}
return list;
}
The comments on your OP have pretty much already answered your question, I'll just provide some extra insight.
You have a List that contains Students objects. You populate this List by creating a Students object and adding that object to the List for every result that's in rs. How would you go about doing this if you just made one Students object? You've gotta make as many objects as there are results in rs in order to do what it is you're trying to do. This is pretty much what always happens with these data structures, unless it's an array.
that someone is right at some cost of heavy coding. It is not really needed to create a new object . you can always use the same student object and use set to new values and add to list. Sorry I was about to same object with different references....! Copy pasted and missed to add the code inside the loop ! The edited is was i meant
public static List<Students> selectFromDatabase(Connection conn, Statement stmt){
List<Students> list = new ArrayList<Students>();
String select = "SELECT * FROM students";
ResultSet rs = null;
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(select);
Students student = null;
while(rs.next()){
student = new Students();
//you have to create a new OBJECT FOR EACH LOOP
student.setStudentId(rs.getInt(1));
student.setName(rs.getString(2));
student.setGpa(rs.getInt(3));
list.add(student);
}
}catch(SQLException e){
System.out.println(e.getMessage());
}
return list;
}

Iterate 2D array of ResultSet to JTable

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 to Array

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!

How to change String Array to ArrayList in java

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"));
}

Categories

Resources