servlet show only one data from database not all - java

public static getset getdata(){
getset gs=new getset();
byte img[]=null;
ServletOutputStream sos=null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","admin");
PreparedStatement stmt=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next()){
gs.setId(rs.getInt(1));
gs.setName(rs.getString(2));
gs.setCountry(rs.getString(3));
gs.setImg(rs.getBytes(4));
}
}catch(Exception e){System.out.print(e);}
return gs;
}
NewClass nc=new NewClass();
getset a=nc.getdata();
out.println(a.getId());
out.println(a.getName());
out.println(a.getCountry());
out.println("<img src="+a.getImg()+" width=300 height=300></img>");
above is my code for retriving data form database
when i rum the code it show me only one data i.e the last data from database
and when i use (if condition ) it shows me first column data why? i cannot understand while i searched but did not found any solution .
getset is the class for getter and setter.

You are creating only one object , and in the while loop overwriting it every time instead of creating a new object.
getset gs=new getset();
You should create a new object in the while loop every time, set the values and then add the object to a list for example. Then iterate and print that list to test how it goes.
So, this should be the first statement in the loop gs=new getset(); (if you have gs declared outside of the loop and set to null) and then add gs to a list at the end of the loop (inside, not outside).

You are setting/saving only one object inside while/if,
When using if, you are entering at the first time only
When entering while loop, you are overriding values until the last data update.
For getting multiple values add data to List for example

Related

How to turn a ResultSet into a DTO ArrayList

I have a ResultSet from a Database that contains 6 columns for each row.
For me, each row is an object and each column is a parameter for that object.
The question is, I'm trying to do it with this code:
while(rs.next() && i<25){
aux.setIdVinilo(rs.getInt("id_vinilo"));
aux.setTitulo(rs.getString("titulo"));
aux.setAutor(rs.getString("autor"));
aux.setGenero(rs.getString("genero"));
aux.setFecha(rs.getInt("fecha"));
aux.setDiscografica(rs.getString("discografica"));
aux.setImagen(rs.getString("imagen"));
historial.add(aux);
i++;
}
rs is the ResultSet, historial is the ArrayList and aux is my DTO consisting of the fields shown.
The problem with this is that it ends up filling the ArrayList with the same information 25 times. So I guess that rs.next() does not move one row forward after each iteration. How do I achieve this?
The problem is you are setting the same object again and again
You need to create a new object inside loop
while(rs.next() && i<25){
DTO aux=new DTO();// create aux object here
aux.setIdVinilo(rs.getInt("id_vinilo"));
aux.setTitulo(rs.getString("titulo"));
aux.setAutor(rs.getString("autor"));
aux.setGenero(rs.getString("genero"));
aux.setFecha(rs.getInt("fecha"));
aux.setDiscografica(rs.getString("discografica"));
aux.setImagen(rs.getString("imagen"));
historial.add(aux);
i++;
}
Create DTO object inside the while loop

Why does my SQL while(set.next()) skips the first element?

I execute:
select * from table_name order by column desc;
And I want to go through the items sequentially. I got the ResultSet from that and did:
while(set.next()) {
// processing code
}
Unfortunately, that skips the very first element. What's the best way to iterate through the entire ResultSet and include the very first element?
Use:
set.beforeFirst();
while(set.next()) {
// Your code
}
This will run the body of your loop once before advancing the ResultSet. You don't want to use a do loop (my previous answer) because it will throw an Exception if the query has 0 rows returned.
I know this is really old but my search hit here and after the solution didn't work for me (forward only result set) I believe the issue was never really addressed. In my case, I was doing:
jdbcTemplate.query(sql, rs -> {
while(rs.next()) {
// processRow
}
// no return statement
, args);
I then looked more closely at the method that was being called and the second argument was a "RowCallbackHandler" and not a "ResultSetExtractor" so the correct use of this code is:
jdbcTemplate.query(sql, rs -> {
// processRow
}, args);
This does the "while (rs.next())" loop for you.
I'd wager the OP was doing the same thing I was.
Your code is correct and you are not loosing any records. In the SDK Documentation for ResultSet you can read that:
"A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set."
Only case were you could loose records if you do a resultSet.next() before the one you are showing.
Whenever next() is called, it reads a record from result set.
if (!set.next() ) {
System.out.println("no data");
} else {
do {
//statement(s)
} while (resultSet.next());
}

null pointer exception can't be fixed

I'm implementing a software for a stock management system in java.I'm using MVC design pattern and i found this exception when trying to fill a JcomboBox. I want to get all the batches when a item-code is being passed into the method.so the method should return a array-list of relevant objects. but when I run this program it gave me this kinda error and it says there is empty result set. but i also tried the sql code manually in the terminal and it worked. so i can't imagine how to fix this error. i'm glad if anyone can tell me where is the problem. I tried to post my screen shots but it cannot be done as i don't have enough reputation
here is my code
String sql = "select batchNo from MainBatch where itemCode = ?";
Connection c=DBConnection.getInstance().getConnection();
PreparedStatement ps=c.prepareStatement(sql);
ps.setString(1, itemCode);
System.out.println(itemCode+" -----> item code is thiss");
ResultSet set=ps.executeQuery();
ArrayList<MainBatch> list=new ArrayList<>();
System.out.println(set.next()+" <-----result set is");
while (set.next()) {
MainBatch batch=new MainBatch(set.getString("batchNo"));
list.add(batch);
}
return list;
[
ResultSet.next() moves the result set's cursor to the next row. When you print it, before the while loop, you're losing the first row (or the only row in a single row result set). Personally, I'd just omit it, but if you have to have it, you could extract the result to a local variable:
boolean next = set.next();
System.out.println(next + " <-----result set is");
while (next) {
MainBatch batch=new MainBatch(set.getString("batchNo"));
list.add(batch);
next = set.next();
}
return list;
Remove this line.
System.out.println(set.next()+" <-----result set is");
You are calling set.next() twise, this moves the resultset pointer to next row.

How to use a get method for a SQLite Database management class in another class?

What I am trying to do is retrieve an ArrayList from another database manager class. Unfortunately all I can do because the manager class cannot work statically is create an instance in another class, then call the method. Then I got myself into passing that same instance into the method which asked for an SQLiteDatabase object. Now I've worked myself into a bind of confusion, when all I really want is to do is retrieve the arraylist to display a listview of elements from an SQL column.
EDIT: My post lacked clarity, so I'll try to specify exactly what is going wrong and what I am trying to accomplish here:
In a display (output) activity, I am trying to use a ListView to display elements contained in an SQL database. Currently, I am only focusing on one column (Assignment Names). My approach involved using a get method built into the database manager class, but because you cannot reference that method statically, I tried to use the method by creating an instance of that manager class. This would return an ArrayList of Inputted objects (each containing a name). It seemed to have worked, but when running the program, the LogCat protested that I was calling getDatabase recursively. After looking online, people recommended that I fix the issue by changing the method to ask for (SQLiteDatabase db) as parameters so the same database gets tossed around in the manager. Now I get confused here-- I'm not sure what to pass into this method from the display activity. It also doesn't help that from what I've heard from the comments, my get method doesn't traverse the SQL database properly. If you can solve this puzzle THANK YOU!
I'll post my code for diagnosis, hopefully an outside view will show exactly what's wrong with everything I'm trying here.
public Cursor getAssignmentNames(SQLiteDatabase db) {
return db.query(false, ASSIGNMENT_TABLE, COLUMN_TITLES,
" WHERE " + ASSIGNMENT_NAME + " ", null, null, null, " ORDER BY "+ASSIGNMENT_URGENCY_RATING, null);
}
/
public ArrayList<Inputted> getListOfAssignments (SQLiteDatabase db) {
Cursor names = getAssignmentNames(db);
ArrayList<Inputted> assList = new ArrayList<Inputted>();
names.moveToFirst();
while (!cursorsAreAfterLast(names) ) {
int go = 0;
assList.add(new Inputted(names.getString(go))
names.moveToNext();
go++;
}
return assList;
}
/
DBRecordsLayer assignmentRecords = new DBRecordsLayer(this,
"assignment.db", null, 1);
ArrayList<Inputted> assList = DBRecordsLayer.getListOfAssignments(assignmentRecords);
Your code is a bit confusing... In each iteration of the while loop, you are incrementing the cursor (names.moveToNext()); You are also incrementing go.
The result would be:
1st iteration: You are taking the data from the first column of the first query
2nd iteration: You are taking the data from the second column of the second query
etc...
I'm assume that you want to be reading data from the same column of the database for each iteration.
try this:
public ArrayList<Inputted> getListOfAssignments (SQLiteDatabase db) {
Cursor names = getAssignmentNames(db);
ArrayList<Inputted> assList = new ArrayList<Inputted>();
names.moveToFirst();
columnContainingStringToSendToInputtedConstructor = x; //replace the x with column you need from your table
while (!names.isAfterLast()) {
assList.add(new Inputted(names.getString(columnContainingStringToSendToInputtedConstructor));
names.moveToNext();
}
}

Retrieving multiple values from an arraylist

I have saved values retrieved from a database in java to an arraylist.
I have used a class to save the data to the array list as shown below.
ArrayList<NewSms> details = new ArrayList<NewSms>();
try{
Statement query = conn.createStatement();
ResultSet result = query.executeQuery("Select `senderAddress,message,linkid from sdp_smsincoming where status=0 AND smsServiceActivationNumber =1234 ");`
while(result.next()){
String address = result.getString("senderAddress");
String message = result.getString("message");
String linkid = result.getString("linkid");
NewSms smsdetails = new NewSms();
smsdetails.set_address(address);
smsdetails.set_message(message);
smsdetails.set_linkid(linkid);
details.add(smsdetails);;
}
}
However i now want to retrieve the values individually per row,from another class in the program.How can i do this?By individually i mean getting the address,message and linkid per row in the arraylist.
However i now want to retrieve the values individually per row,from another class in the program.How can i do this?
You just access each NewSms in the list. To access one by index, you could use:
NewSms sms = details.get(2); // Or whatever
// Now access the properties of sms
Or to access each of them in turn, use an enhanced for loop:
for (NewSms sms : details) {
// Now access the properties of sms
}
Note that to comply with Java naming conventions, your NewSms class should have methods such as getAddress, setAddress - not set_address.
Also note that you need to close your result set / statement / connection - if you're using Java 7, you can use a try-with-resources statement; otherwise you should use finally blocks.
EDIT: If your problem is actually just returning the list, that's easy:
public List<NewSms> loadSmsDetails() {
// Code as before...
return details;
}
Then just call it from your other class:
// Where repository is a reference to an instance of the class containing the above method
List<NewSms> allDetails = repository.loadSmsDetails();
for(NewSms smsdetails:details){
String address = smsdetails.get_address();
String message = smsdetails.get_message();
String linkId = smsdetails.get_linkid();
}
However i now want to retrieve the values individually per row,from
another class in the program
You need to pass the arraylist to the another class and iterate over it there to get the individual elements. The idea is to use a common araylist - to store the values from the resultset and in another class to iterate through them.

Categories