Java ResultSet next() and previous() buttons are not working - java

Hey guys I'm trying to scroll through the rows in my database. For some reason my previous and next buttons are not working. Next button displays just first row and previous button doesn't display anything. My first and last buttons are working.
private void previousbtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("SELECT * FROM EMPLOYEE");
if (rs.previous())
{
str1 = rs.getString("emp_id");
emp_id.setText(str1);
str2 = rs.getString("emp_fname");
first_name.setText(str2);
str3 = rs.getString("emp_lname");
last_name.setText(str3);
}
else
{
rs.next();
}
con.close();
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(EmployeeGUI.this, err.getMessage());
}
}
private void nextbtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select * from employee");
if (rs.next())
{
str1 = rs.getString("emp_id");
emp_id.setText(str1);
str2 = rs.getString("emp_fname");
first_name.setText(str2);
str3 = rs.getString("emp_lname");
last_name.setText(str3);
}
else
{
rs.previous();
}
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(EmployeeGUI.this, err.getMessage());
}
}

Here's the javadoc for ResultSet and this is what it says:
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.
So, when you get the ResultSet object, it will always be placed before the previous row and hence, previous() will always return false.
Assuming you are trying to implement Pagination with these buttons, I would recommend having a look at MySQL SELECT documentation and use limit to get the rows, e.g.:
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
You can use it with LIMIT i, 1 where i will increment with each click of next and decrement with each click of previous.

Related

SQLite DELETE query won't delete from database

Here's my code for the addStudent:
#FXML
private void addStudent(ActionEvent event) {
// sql query to insert data into students at ID, first name, last name, email and DOB
String sqlInsert = "INSERT INTO students(id,fname,lname,email,DOB) VALUES (?,?,?,?,?)";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sqlInsert);
// add the data in the right column
stmt.setString(1, this.id.getText());
stmt.setString(2, this.firstname.getText());
stmt.setString(3, this.lastname.getText());
stmt.setString(4, this.email.getText());
stmt.setString(5, this.dob.getEditor().getText());
stmt.execute();
conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
And here's my code for removeStudent:
#FXML
private void removeStudent(ActionEvent event) {
try {
// sql query to delete data from the database
String sqlRemove = "DELETE FROM students WHERE id = ?";
// open a connection to the database and use PreparedStatement to
// initialize the query.
Connection conn = dbConnection.getConnection();
PreparedStatement delete = conn.prepareStatement(sqlRemove);
// information needed to delete the row
delete.setString(1, selectStudent());
// execute and delete
delete.executeUpdate();
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// update table after deleting
loadStudentData(event);
}
The picture above is the view of my table. I hit LoadData and my table values show up. I want to be able to click on a row(student) and hit Delete Student to remove it.
Helper method for removeStudent:
private String selectStudent() {
String result = "";
try {
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
result = rs.getString(1);
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
return result;
}
I'm pretty sure it has to do with when I "click" on a row, the id value for that isn't being held anywhere so when I hit "Delete" nothing is being given for it to Delete.
I don't know. Any advice would be awesome. :D
First edit: nothing is assigned to delete.setString(1, this.id.getText()). When I click on the row and hit delete, nothing is happening because there's nothing being assigned to id when I click on the row. The query string DOES work however when I physically give it an ID to delete. Also verified that the button does work; it prints out a lovely message for me with a good ol' System.out.println("expletive");
Second edit: Ok, so I updated the removeStudent code and now all I get is the string "null" returned. Nothing deletes. Nothing updates. Nothing is happening except I get "null" in the console.
Third edit: Getting closer! With the realization that the removeStudent isn't being given an ID to delete, I decided to create a private helper method that will do a SELECT query. Now, when I hit delete, it'll delete....but from the top, and not at where I want it selected. The code is above.
Fourth edit: Getting even closer! So, I figured out how to capture the row I click on within the table and I can delete......however, because of my sqlRemove command, I'm deleting by id so if I click on a row with index 3, then ONLY the row within the table that has an id of 3 will be deleted, nothing else. I gotta re-write how the sqlRemove command is worded.
I fixed it:
private String selectStudent() {
// initial value for result to return
String result = "";
// grab the index of the row selected on the table
int initial = studenttable.getSelectionModel().getSelectedIndex();
try {
// SELECT query to execute
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
// while there's a next row
while(rs.next()) {
// set temp to equal the id rs.next() is currently on
String temp = rs.getString("id");
// get the row id - 1 since we start at 0
int temp1 = rs.getRow() - 1;
// if temp1 is equal to the index we selected
if(temp1 == initial) {
// make it equal to result
result = temp;
}
}
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// return the row to delete
return result;
}
What's going on is in the comments. I finally figured out how to pass the value from a selected row and compare it to a row. Once I get the correct row to pass, I give it to the delete function to remove.
After a day in a half.............but I love it, so. Yeah.

Java: SQL Query: rs.next() is false after updating a column

I have a strange problem. I have a database and I want to change the values of a column. The values are safed in an Arraylist (timelist).
In order to write the values in the right row, I have a second Arrylist (namelist). So I want to read the first row in my Database, than I check the namelist and find the name. Than i take the matching value out of the timelist and write it into the database into the column "follows_date" in the row, matching to the name.
And than I read the next row of the Database, until there are no more entries.
So the strange thing is, if I change nothing in the database, the while(rs.next()) part works.
For example:
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //liest die namen
}
}
This would print me every name after name. But when I change the table, the while loop ends after that. (no error, the program just finishes)
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //writes the name
//look, if name is in Arraylist "namelist"). if yes, than write the matching date from "timelist" into the database.
if (namelist.contains(name)){
System.out.println("name found: "+ name);
int listIndizi = namelist.indexOf(name); //get index
Long indiziDatum = (long) timelist.get(listIndizi); //get date from same Index
System.out.println(indiziDatum); // print date so i can see it is correct (which it is)
statement.executeUpdate("UPDATE users SET follows_date ="+ indiziDatum +" WHERE username = '"+name+"'"); //updates the follows_date column
}
}
Everything works fine, except that now, the while loop doesn't continues after the first passage, but ends.
The resultSet of a statement is closed and will not return further results if you execute another statement. Create a new separate statement object for the update and everything should work as excepted.
Statement statement1 = connection.createStatement();
Statement statement2 = connection.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SELECT username FROM users");
while(resultSet1.next()){
...
statement2.executeUpdate("UPDATE users ..."));
}
As to Why it happens:
Here is the explanation from the official documentation:
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
Alternative Approach:
From your sample, it seems you are trying to update the "same" row in your resultSet, you should consider using an Updatable ResultSet.
Sample code from the official documentation:
public void modifyPrices(float percentage) throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
"SELECT * FROM " + dbName + ".COFFEES");
while (uprs.next()) {
float f = uprs.getFloat("PRICE");
uprs.updateFloat( "PRICE", f * percentage);
uprs.updateRow();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}

Retrive a single value via resultset and compare it with a String value

I have a table with this columns (id,name,isbn,borrowedStatus(varchar),Date) and some rows in my table.
Now i want to get borrowedStatus value for a specific id,then i need to recognize that String (yes, or no).
Here is my code:
public void booksTableBorrowChanged(int rowInModel) {
Object bookId = this.getValueAt(rowInModel, 0);
Connection con;
PreparedStatement ps1;
String query1 = "select borrowedStatus from books where id=" + bookId;
ResultSet rs = null;
try {
con = DriverManager.getConnection(...);
ps1 = con.prepareStatement(query1);
rs = ps1.executeQuery();
if (String.valueOf(rs.getString("BorrowedStatus")).equalsIgnoreCase("No")) { // then do Borrow Action
System.out.println("Old statuse : No");
// then do other stuff
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
But this code has this exception when executed:
java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
...
How can i solve this problem?
From ResultSet's Javadoc:
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.
Notice the sentence starting with "Initially": You first have to call next before being able to access any data.

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()

compare integer text field value with mysql data in java

I want to check whether the newly entered data is already in the table
code:
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
Error :
Exception:java.sql.SQLException: Illegal operation on empty result set.
You need to check if the result set has elements or not:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
You get this exception when the select statement returns an empty set. Add a try/catch block which acts upon the knowledge that the data is not already in the table in the catch block.
You need to check the ResultSet first to check to see that it contains rows:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
The easiest way to check whether a particular record exists in the database might be just as follows:
Select 1 from bank where No = [your_supplied_value]
This query would return 1 if it finds a row in your database with the supplied data or return an empty resultset. So, all you need to check is whether ANY value is returned in the resultset or whether it is emtpy.
Here's a sample code to get you started:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
I hope this is not your final code, because there're several problems with it:
You're not managing your resources properly. Once you're done querying your database, you should consider closing your resultset, statement and connection objects.
Note that I checked whether the text in the JTextField is empty or not. This is a good way of preventing a call to the database when you know that the text field had no value in it.
I would suggest using a PreparedStatement rather than a Statement for querying to your database.
A ResultSet is initially positioned before the first row. So you need to call next() to move it to the next row (and check that it returns true) before you call one of the getXXX() methods.
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}

Categories