Displaying next row details from database when next button is pressed - java

I am working in a project known as Employee attendance management system.For this I had created a java form.The form contains employee ID,employee name fields,next button.
If I press next button the next employee details has to be displayed in the above two fields.In order to do this I had used for loop the problem hear appears is it is displaying last employee details from the database.
My code is:
int i=1;
try {
ResultSet rs;
Connection con;
Statement st;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:vasu");
st = con.createStatement();
for(i=1;i<=5;++i){
rs = st.executeQuery("select ID,EName from attendence where ID="+(i));
while(rs.next()) {
t1.setText(rs.getString("ID"));
t2.setText(rs.getString("EName"));
}
}
}
catch (Exception e) {
}
Sorry for my poor english.
Could any one please help me..
Well Thanks in advance.

There is problem in this loop
while(rs.next()) {
t1.setText(rs.getString("ID"));
t2.setText(rs.getString("EName"));
}
you need to store the values from database in an array and then iterate over it with your (prev,next) button like
i=0;
while(rs.next()) {
dataset["id"][i]=(rs.getString("ID");
dataset["EName"][i]=rs.getString("EName");
i++
}
to display information you can use dataset array like
t1.setText(dataset["id"][i]);
I have not checked syntax but the logic is correct.

The values are being overwritten each time in t1 and t2 when you call the loop. This is why the last record value is being displayed.

Related

While Loop inside an If-else statement (Java)

I'm writing a Java program in which it updates existing data in a local database with new details whenever a record that has the same product model in another database is found. If no record is found, it inserts a new record instead.
I'm using an if-else statement to check if record does exist or not. The current code works ONLY for a single record. I want it to keep on updating the local database as long as the product model in local database and in the other database exists.
Here's the code, I'm currently using:
public static void checkExist() {
try {
Statement stmt = conn.createStatement();
int prod_qnty, prod_weight;
float prod_price;
String prod_model = "97801433"; //testing purposes
ResultSet rs = stmt.executeQuery("SELECT * from products where products_model = " + prod_model );
if (rs.next()){
//while (rs.next()) {
prod_qnty = rs.getInt("products_quantity");
prod_price = rs.getFloat("products_price");
prod_weight = rs.getInt("products_weight");
System.out.println(prod_qnty + "\t" + prod_price + "\t" + prod_weight);
updDB(prod_model, prod_qnty, prod_price, prod_weight);
//}
}
else{
insertDB(prod_model, prod_qnty, prod_price, prod_weight);
}
stmt.close();
} catch (SQLException ex) {
//Logger.getLogger(Check.class.getName()).log(Level.SEVERE, null, ex);
}
}
I've added a while loop within the if statement where record exists, however, after I've added the while loop. Now it can't even print out any record. It seems like once it goes inside the if (rs.next()) condition, it doesn't go inside the while loop.
Will anyone let me know what I'm doing wrong? Is it possible to use a while loop inside an if-else statement? As usually it is used the other way around, if-else statement within the while loop.
Any help will be greatly appreciated. Thank you.
You do not have to add a separate if statement while (rs.next()) { //CODE }
if you call next() 2 times, cursor will move 2 records forward and if you have only one record for the query, it will not go into the while loop.
CODE will execute only if there is a results remaining.

Resultset can not be traversed

I want to use while(rs.next()) to traverse the UserInfo table. There are seven records in UserInfo table, but I only got the first record. After I had joined the codes of rs.getRow();, I got the result what I want.
try{
Statement stmt=conn.createStatement();
String queryStr="SELECT * FROM UserInfo";
ResultSet rs=stmt.executeQuery(queryStr);
while(rs.next())
{
String strName="Name is "+rs.getString(3)+";";
String intAge="Age is "+rs.getInt(5)+";";
String strCompany="Company is "+rs.getString(4)+".<br>";
//int rowNum=rs.getRow();
out.println(strName+intAge+strCompany);
}
out.println("Succeed in visiting UserInfo table.");
}catch(SQLException e){
out.println("Failed to query.");
}
I don't want to use rs.getRow();. How should I deal with this problem?
Your code does appear to be fine except the String part.If you are using String to hold a record, then you wouldn't be able to display all 7 records.
Thus try using collection object like ArrayList. And of course you should close connections in finally block.
try{
Statement stmt=conn.createStatement();
String queryStr="SELECT * FROM UserInfo";
ResultSet rs=stmt.executeQuery(queryStr);
List<String> list = new ArrayList<String>();
while(rs.next()){
list.add(rs.getString(3));
}
System.out.println("rows "+list.size());
}catch(SQLException e){
out.println("exception "+e.getMessage());
}
finally{
rs.close();
stmt.close();
conn.close();
}
This is good example of how you should be retrieving values from database using collection object.
http://theopentutorials.com/tutorials/java/jdbc/how-to-retrieve-all-rows-from-mysql-table-using-jdbc/
rs.next() Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row;
rs.next only tells you if there is a next record.
When you run
ResultSet rs=stmt.executeQuery(queryStr);
This already places the data from the first record into variable rs.
In order to advance to the next record you need to run rs.getRow but only if there is a
next record (check with rs.next).

How to move data from database in textfield using next button in java

here is the code for next button
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt)
{
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
String srt="jdbc:derby://localhost:1527/silicon";
con=DriverManager.getConnection(srt,"rock","brock");
ps=con.prepareStatement("select * from stu where id="+jTextField1.gettext(),
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs=ps.executeQuery();
if(rs.next()) {
jTextField1.setText(String.valueOf(rs.getInt("id")));
jTextField2.setText(rs.getString("nam"));
jTextField3.setText(rs.getString("qu"));
jTextField4.setText(String.valueOf(rs.getInt("pr")));
jTextField5.setText(String.valueOf(rs.getInt("mob")));
jTextField6.setText(String.valueOf(rs.getInt("ad")));
}
else
{
JOptionPane.showMessageDialog(new studentf(), " no record record to navigate in text field");
}
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());</i>
}
}
as you see the code i want such way of coding that whenever i click on next button i just move to next record i try most of options which is available every i searched all the topics here but none of them helps me to find my solution i just want on the click on next button the data on Text field changes to next record mean it shows next record i got a project over this i done add search delete first last only 2 buttons unable to do next and
previous button .please help
It looks like there are a good few issues with this code, but I will talk about the most obvious. Excuse my ignorance if I am understanding it wrong, but if your current code executes each time the button is pressed then you are getting a fresh new ResultSet each time, and so each time you press the button your going to display the first result from the new results set.
You need to call rs=ps.executeQuery(); outside of this method so that your not redefining the rs each time. That way calling if(rs.next()){} will move to the next result rather than navigating to the first result each time.
Make the following instance variables;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
and add following into a constructor (or the like);
Class.forName("org.apache.derby.jdbc.ClientDriver");
String srt = "jdbc:derby://localhost:1527/silicon";
con = DriverManager.getConnection(srt,"rock","brock");
ps = con.prepareStatement("select * from stu",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = ps.executeQuery();
A word of warning, you will have to think of a way to close your connection by calling con.close();. You could call con.close() inside of your #Override protected void finalize(){} but there is no 100% guarantee that method will run when your objected is cleared up by the GC.
I hope this helps.
Edit: It seems as though you have a lot of questions about JDBC and PreparedStatements. Here are links to the Oracle JDBC and PreparedStatement tutorials if you need some further reading. A more comprehensive understanding of the subject might be in order.

Java Code for the next button

Hi this is my java code for next button.
but it goes onto only 1 record i.e after the last record it moves to the 1st one only.
how to move it through the entire database entries.
plz provide me some suggestions.
public void Next() {
Connection con = null;
ResultSet rs = null;
try {
con = DBConnection();
PreparedStatement pstmt = con.prepareStatement("select * from data", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
if (rs.next()) {
field1.setText(rs.getString("Name"));
field2.setText(String.valueOf(rs.getInt("Age")));
} else {
rs.previous();
JOptionPane.showMessageDialog(nxtbtn, "end of file");
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
rs.close();
} catch (SQLException err) {
JOptionPane.showMessageDialog(nxtbtn, err.getMessage());
// TODO: handle exception
}
}
}
When you call next, it reloads all the results from the database and moves the cursor to just before the first row, calling rs.next will move to the first row.
Do you're query once, presumably when you need to display the next record.
In your next method, simply call rs.next() to move the cursor to the next available row in the result set.
Of course, you'll need continue to manage the error states ;)
you need to get the resultset out side of the next() method. calling next() every-time resets the resultset, and cursor moves to start again.
if understand it correctly you want to use the next button to click throup the resultset?
then you shoul read the database an have it stored in your resultset outside the next button method.
at the moment it seems that your making a new resultset with every click and only reading the first set of data.
private Connection con = DBConnection();
private ResultSet rs = null;
private Statement stmt = null;
public void onLoad()
{
stmt = con.createStatement();
rs = stmt.executeQuery("YOUR-CODE-HERE");
}
and now in the next method go through the rs with each click
rs.next() move the cursor to the next available row.thats why it show one record. use while(rs.next())
Move one record forward like below
rs.next()
Move through all the 'next' records like below
while(rs.next())
Move back like below
rs.previous()

Storing Result set into an array

i know this should be simpel and im probably staring straight at the problem but once again im stuck and need the help of the code gurus.
im trying too take one row from a column in jdbc, and put them in an array.
i do this as follows:
public void fillContactList()
{
createConnection();
try
{
Statement stmt = conn.createStatement();
ResultSet namesList = stmt.executeQuery("SELECT name FROM Users");
try
{
while (namesList.next())
{
contactListNames[1] = namesList.getString(1);
System.out.println("" + contactListNames[1]);
}
}
catch(SQLException q)
{
}
conn.commit();
stmt.close();
conn.close();
}
catch(SQLException e)
{
}
creatConnection is an already defined method that does what it obviously does.
i creat my result set
while theres another one,
i store the string of that column into an array.
then print it out for good measure. too make sure its there.
the problem is that its storing the entire column into contactListNames[1]
i wanted to make it store column1 row 1 into [1]
then column 1 row 2 into [2]
i know i could do this with a loop. but i dont know too take only one row at a time from a single column. any ideas?
p.s ive read the api, i jsut cant see anything that fits.
You should use an ArrayList which provides all the logic to automatically extend the array.
List rowValues = new ArrayList();
while (namesList.next()) {
rowValues.add(namesList.getString(1));
}
// You can then put this back into an array if necessary
contactListNames = (String[]) rowValues.toArray(new String[rowValues.size()]);
Did you mean something like:
int i = 0;
ResultSet rs = stmt.executeQuery("select name from users");
while (rs.next()) {
String name = rs.getString("name");
names[i++] = name;
}

Categories