ResultSet.next() row counter fails to count - java

I'm trying to figure out why this won't count and show Rows: 2 when I enter "ashton" for username and "ashton" for password. In my database I inserted 2 entries of username and password.
Here's the screenshot of table:
Here's the GRAB file:
Here's my code:
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String userNameEntered = userNameTxtField.getText().trim();
String passwordEntered = passwordTxtField.getText().trim();
if(userNameEntered.isEmpty() || passwordEntered.isEmpty()){
JOptionPane.showMessageDialog(this, "Please fill out all fields");
}
else{
String username = "jordan";
String password = "jordan";
String dbURL = "jdbc:derby://localhost:1527/JDBCSTUDY";
Connection myConnection = null;
ResultSet myRs = null;
String SQL = "SELECT * FROM USERS WHERE USERNAME = ? AND PASSWORD = ?";
try {
myConnection = DriverManager.getConnection(dbURL,username,password);
JOptionPane.showMessageDialog(null, "Successfully Connected To Database");
PreparedStatement myPrepStmt = myConnection.prepareStatement(SQL,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
myPrepStmt.setString(1,userNameEntered); //assigns a string value to the first ?
myPrepStmt.setString(2,passwordEntered); //assigns a string value to the second ?
myRs = myPrepStmt.executeQuery(); // executes the select query and stores it to myRs
if(myRs.next() == false){//next() method returns true if the select statement is satisfied or if query is valid
JOptionPane.showMessageDialog(this, "Not found");
}
int countRows = 0;
while(myRs.next()){
countRows++;
if((myRs.getString(2).equals(userNameEntered))
&& (myRs.getString(3).equals(passwordEntered))){
JOptionPane.showMessageDialog(this,"found" +"\nRows: " + countRows );
}
}
} //end of try
catch (SQLException e) {
//if an exception or an error even occured while executing the try{} block, the 3 lines will be printed
System.err.println("Error message: " + e.getMessage());
System.err.println("Error Code: " + e.getErrorCode());
System.err.println("SQL State: " + e.getSQLState());
}
finally{
if(myConnection!=null){
try {
myConnection.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,"Error encountered: " + ex.toString());
}
}//end of if
}//end of finally
}
}
In my understanding, next() returns true if the SELECT query is successful or if there are rows when cursor is moved by next(). I need to be able to count the rows to show that there are more than 1 row holding the same username and password. I can't proceed on making another ifelse for counting duplication of username and password because in my code, it doesn't seem to count 2 rows.
I'd appreciate any help.
Thanks.
this is the output i get,
This is what I did, and it worked. Thanks for the suggestions guys! It's helping me learn more.
int countRows = 0;
while(myRs.next()){
countRows++;
}
if(countRows == 0)
{
JOptionPane.showMessageDialog(this, "User details doesn't exist. \n Please register first");
}
else if(countRows > 1) //if there are duplications
{
JOptionPane.showMessageDialog(null, "User details found but has more 1 one entry" +
"\nFound: " + countRows + " users" );
}
else if(countRows == 1){
JOptionPane.showMessageDialog(null, "User Found");
}

Your error is to call rs.next twice: Every time you call next you are implicitly discarding the last state of the cursor. It's a good (and clearer) practice to read the resultset's columns after every call to next.
In your case, it's enough to move if after the while loop, changing the condition:
int countRows = 0;
while(myRs.next()){
countRows++;
...
}
if (countRows==0)
{
JOptionPane.showMessageDialog(this, "Not found");
}

The main problem is you call myRs.next() two times before getting data.
You can use
myRs.isBeforeFirst()
as described here
or use this template as described here
if (!myRs.next() ) {
System.out.println("no data");
} else {
do {
//statement(s)
} while (myRs.next());
}
And you don't need loop at all — just use a SQL request with count
SELECT COUNT(*) FROM USERS WHERE USERNAME = ? AND PASSWORD = ?

Related

How to check if deletion was successful in the database?

I wanted an error to popup, when the user entered a wrong id into the delete field. But even if a wrong id is entered, the query still proceeds, but no data is deleted. Here's my code:
String value = jTextField19.getText();
if (value == null || "".equals(value)) {
JOptionPane.showMessageDialog(null, "The field is blank!");
} else {
theQuery("DELETE FROM inventorydb WHERE item_id=('"+jTextField19.getText()+"') AND item_id IS NOT NULL");
}
The theQuery method:
private void theQuery(String query) {
Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory", "root", "");
st = con.createStatement();
st.executeUpdate(query);
JOptionPane.showMessageDialog(null, "Done!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Error!");
}
}
First of all: do not ever directly build SQL queries from user input, use prepared statements instead. If you don't know about SQL Injection, you should.
If you are using JDBC, you can check the result of #executeUpdate() to see how many rows were affected. If it was zero, then you can say that it was a wrong id.
This is the method definition:
public int executeUpdate(java.lang.String sql)
The return value is:
An int that indicates the number of rows affected, or 0 if using a DDL statement.
In the program at hand, you can just simply do this:
int deleted = st.executeUpdate(query);
if (deleted == 0) {
JOptionPane.showMessageDialog(null, "Nothing to delete!");
return;
}

Validation in delete query in java

I have a problem in validating my delete query anything I type even if the data is not on my database it keeps deleting it says success I want it to have an error if the user type a data that is not exists in the database. Here's my code:
try{
System.out.println("Enter record you want to delete: ");
frail = scn.nextLine();
}catch(Exception ee){
System.out.println(ee.getMessage());
}
try{
stmt = conn.createStatement();
String sqlII = "delete from tbl_test where test_name = ?";
PreparedStatement psII = conn.prepareStatement(sqlII);
psII.setString(1, frail);
psII.executeUpdate();
int rowAffacted = psII.executeUpdate();
if (rowAffacted != 0) {
System.out.println("Deleted!");
}else{
System.out.println("No Affected Rows!");
}
}
catch(Exception eer){
System.out.println(eer.getMessage());
}
psII.executeUpdate(); returns an int. If these value is zero, no lines are delete, so you can see that the user exists is not in the database and you can show an error. Is the user is corect, the value should be grater than zero.
int noOfAffectedRows =psII.executeUpdate();
if (noOfAffectedRows = 0){
//show Error
}
You could catch the return value of executeUpdate as below:
int rowAffacted = psII.executeUpdate();
if (rowAffacted != 0) {
System.out.println("Deleted!");
}
Javadoc for executeUpdate's return value says
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
executeUpdate() returns the number of rows altered or returns 0 in case no rows are affected, so in your case you can do something like:
int alteredRows=psII.executeUpdate();
if(alteredRows==0)
{
System.out.println("No rows deleted");
}
else
{
System.out.println(alteredRows +"rows deleted");
}

Check username and password with MySQL

I am trying to verify username and password with MySQL. But it's not working. I can't find the problem. Can anybody help me fix it?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String user = jTextField1.getText();
char[] pass = jPasswordField1.getPassword();
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
while (rs.next())
{
if (user.equals(rs.getString("username")))
{
if (pass.equals(rs.getString("password")))
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}
Actually I think it is not checking the enteries with username and password in database. am I right?
Firstly, select by username, then hash the user entered password en check if it matches the hashed password in the database. I suggest something like SHA-2
I also suggest you write classes to handle your code, i.e a User class..
You also forgot to close your ResultSet
One more thing, use PreparedStatement
You are checking for password and username match 2 times.
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
There you already check the password and user, First you shuld check if the password its not stored as MD5 or any other hash type
After that sql you only need to check if its returns any row like #Prabhakaran says
Check code which is written is connecting to database, password is not there in the below code
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Second is check the user and pass variable is getting the value from the action event.
Do like this
Statement stat = con.createStatement();
user = user.toLowerCase();
pass = pass.toLowerCase();
String sql = "Select * from tbl_User Where LOWER(username)='" + user + "' and LOWER(password)='"+pass+"'";
rs = stat.executeQuery(sql);
if(rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
First things first.
Code will only be used to validate the error. So you must paste the error fired by your program.
Since we don't have enough information to the problem, I will try to help you out.
1- It seems your connection variable missing the "Connection" try this :
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"DATABASENAME"?useTimezone=true&serverTimezone=UTC","USERNAME","PASSWORD");
2 - You already made the if statement to the query in the beginning, so you don't have to start all over again with You can simply type :
if (rs.next()) {
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
} then carry on with the exception part
this is the code :
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
if (rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}`

Exhausted Result Set

I am developing a project for Online Banking System. I want to retrieve a data from database using JDBC. However, it is showing Exhausted result exception though the query is returning a row in SQLPlus. Please Help. Here's the Code:
try
{
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "hr", "XXXXXX");
String pass = 'sid';
String user = 'sid';
String accountnumber = '2345';
String sql = "select * from user_info where account_number=?";
s1 = con.prepareStatement(sql);
s1.setString(1,accountnumber);
rs1 = s1.executeQuery(sql);
rs1.next();
if(user.equals(rs1.getString("user_name")))
{
if(pass.equals(rs1.getString("password")))
{
if(accountnumber.equals(rs1.getString("account_number")))
{
new AccountInformation(accountnumber).setVisible(true);
}
else
{
JOptionPane.showMessageDialog(this, "Account Number is Incorrect");
}
}
else
{
JOptionPane.showMessageDialog(this, "Password is Incorrect");
}
}
else
{
JOptionPane.showMessageDialog(this, "User Name is Incorrect");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
You threw away your bind parameter when you passed the SQL to Statement#executeQuery - use this one from PreparedStatement...
rs1=s1.executeQuery();
// rs1=s1.executeQuery(sql);
// check if you got a row
if (rs1.next()) {
// as before....
}

Result set code doesn't get executed

I've got the following code to query a database! But the code inside the while loop doesn't get executed! No messagebox, just doesn't get executed! Can anyone help me! Result set is not empty! When I print the same value out of the try catch block it gets executed and the right values get printed! Th DB connection is a standard MySQL DB connection class!
database = new DBConnection();
String dept = txtSearch.getText();
String Query = "SELECT * FROM department where dept_name= '" + dept + "'";
ResultSet set = database.queryDatabase(Query);
try {
if (set.next() == false) {
JOptionPane.showMessageDialog(null, "No Matchs found for the search query! Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE);
} else {
while (set.next()) {
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getCause().toString(), JOptionPane.ERROR_MESSAGE);
}
You're throwing out the first row of your query by calling set.next() and then ignoring the data in the row here:
if (set.next() == false) { // ***** here on this line
JOptionPane.showMessageDialog(null, "No Matchs found for the search query!
Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE);
} else {
while (set.next()) {
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
}
Instead be sure to extract information from your ResultSet every time you call next() and it returns true.
You could do something like this instead:
int setCount = 0;
while (set.next()) {
setCount++;
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
if (setCount == 0) {
// show a warning to the user that the result set was empty
}

Categories