I am implementing a forgot_password type feature on my application and I can not find how to check if I have any rows returned. The user first enters his/her email and then I search the database if the email is found proceed otherwise stop and tell them their email has not been found; This is my code
Connection dbConnection=null;
dbConnection= DB.getConnection();
PreparedStatement preparedStatement= dbConnection.prepareStatement("Select email,password from profiles where email=?");
preparedStatement.setString(1, User_Email);
preparedStatement.executeQuery();
// This code is not working below empty null rows still say email found
if(preparedStatement==null)
{
return ok("Email not found");
}
else
{
return ok("Email Found");
}
The User_Email string works correctly and I have verified but it seems that
preparedStatement==null does nothing
Nah, you're going about it the wrong way. executeQuery() returns a ResultSet. You just need to check if ResultSet has rows.
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
//example
String email = rs.getString(1);
String pw = rs.getString(2);
}
else{
//no results!!
}
Related
image showing my jFrame
I am making a frame which shows records in the sql table one-by-one using text fields as shown. While writing the code for the next button, I need to know the position of the result set to go to the next record. For this purpose, I used a do-while loop with an "if" condition. Following is my code:
try{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";
conn=DriverManager.getConnection(url,userid,pwd);
stmt=conn.createStatement();
String query="select * from emp;";
rs=stmt.executeQuery(query);
String search=jTextField1.getText();
String search1=jTextField2.getText();
double search2=Double.parseDouble(jTextField3.getText());
String search3=jTextField3.getText();
rs.first();
do{
if(rs.equals(new Object[] {search, search1, search2, search3}))
break;
}while(rs.next());
rs.next();
String nm=rs.getString("Name");
String desg=rs.getString("Designation");
double pay=rs.getDouble("Pay");
String city=rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(pay + "");
jTextField4.setText(city);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
But it shows an error "after end of Result Set".
Please help me with this.
Any suggestions to make my code better are also welcome.
Thanks in Advance!!
You can't use ResultSet.equals for this, because that is not what the Object.equals contract is for. It is for checking if an object is equal to another object of the same (or at least compatible) type. A ResultSet will therefor never be equal to an array of object values.
It looks like you want to select a single row from the emp table that matches your search values, in that case the correct solution is to ask the database for only that row. Selecting all rows and then filtering in your Java application is very inefficient, because the database has to send all rows to your application, while finding data is exactly what a database is good at.
Instead, you should use a where clause with a prepared statement:
try (Connection connection = DriverManager.getConnection(url, userid, pwd);
PreparedStatement pstmt = connection.prepareStatement(
"select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {
pstmt.setString(1, search);
pstmt.setString(2, search1);
pstmt.setDouble(3, search2);
pstmt.setString(4, search3);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next() {
String nm = rs.getString("Name");
String desg = rs.getString("Designation");
double pay = rs.getDouble("Pay");
String city = rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(String.valueOf(pay));
jTextField4.setText(city);
} else {
// handle not found case
}
}
}
String email = email_register_txt.getText();
String username = username_register_txt.getText();
Statement stmt = db_connection.connect().createStatement();
String sql = "SELECT * FROM user_profile WHERE username=' "+username+" ' OR user_email=' "+email+" ' ";
res = stmt.executeQuery(sql);
if(res.next()) {
if(res.getString("username").equalsIgnoreCase(username)) {
JOptionPane.showMessageDialog(registerPanel, "The username has already been already registered!");
} else if (res.getString("user_email").equalsIgnoreCase(email)) {
JOptionPane.showMessageDialog(registerPanel, "This email address has already been already registered!");
}
} else { ...
Either of those error message appear when i enter the username/email who has already been inserted into the database.
My register work but I think the verify part may be missing something?
You are obviously not showing all the pertinent code or you simply have neglected to place the needed code into your method that should make this work.
A ResultSet is basically a collection of results from your query which you need to iterate through to access all results from that query. A while loop is widely used as the means to iterate through all the results contained within a result set object. I see nowhere in your code where you have declared a ResultSet Object but yet you are trying to utilize one. Perhaps try something like this:
String email = email_register_txt.getText();
String username = username_register_txt.getText();
try {
Connection conn = DriverManager.getConnection("...your jdbc connection string...");
conn.setAutoCommit(false);
String sql = "SELECT * FROM user_profile WHERE username = ? OR user_email = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, email);
ResultSet res = stmt.executeQuery();
// Utilize a boolean Flag to indicate whether
// or not the User is registered.
boolean registered = false;
while (res.next()) {
if(res.getString("username").equalsIgnoreCase(username)) {
JOptionPane.showMessageDialog(registerPanel,
"The username has already been already registered!");
registered = true;
break; // Get out of the loop. No more need for it.
}
else if(res.getString("user_email").equalsIgnoreCase(email)) {
JOptionPane.showMessageDialog(registerPanel,
"This email address has already been already registered!");
registered = true;
break; // Get out of the loop. No more need for it.
}
}
// Do what needs to be done if User is NOT registered.
if (!registered) {
...............................
...............................
}
res.close();
stmt.close();
conn.close(); //Close the DB connection
}
catch (SQLException ex) {
ex.printStackTrace();
}
You will notice the use of the PreparedStatement Class. There are a number of benefits for using this class:
1) PreparedStatement allows you to write dynamic and parametric queries.
2) PreparedStatement is faster than Statement in Java.
3) PreparedStatement prevents SQL Injection Attacks in Java
Read more about Why to use Prepared Statements in Java here.
I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.
For example:
If TextField1 == to the data in the database.
Output: Swept by GSW.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list WHERE id = ?";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
}
}
}catch(SQLException exc){
System.out.println("Not Found!");
}
Kindly Check the Image Output.
I attached the image file below.
Sample Output
Here are some mistake I see
You use a parameter in the query, "SELECT * FROM item_list WHERE id = ?";so use a PreparedStatement
Set the parameter to that PreparedStatement ps = connection.preparedStatement(query); with ps.setInt(1, Integer.parseInt(TF[0].getText()));
Don't catch the exception without logging it, here your query as a syntax error but you don't know it.
careful with uppercase in the database field name "Id"
This might not be everything ...
And of course, now that you get only the row with that ID, you can simply check if there is at least one row return to validate that it exists.
First of all, you need to log a stack trace of an exception that is thrown. At least you can use exc.printStackTrace() in your catch section.
Second, your issue is that you declared a parameter for your SQL query, but you have not put any value to it.
PreparedStatement p = con.prepareStatement("SELECT * FROM item_list WHERE id = ?");
p.setString(1, TF[0].getText() ); //VALUE_FROM_YOUR_TEXT_INPUT
You don't need to iterate over all result set to check if a user with such id exists. You can just check that result set is not empty.
you can use intValue() for Integer object obvious if your object is not null
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()).intValue() == id){
System.out.println(id);
}
}
You're not setting the value of the id parameter in the statement. Not familiar with Java but in C# it would be something like
statement.Parameters.AddWithValue("#id", id)
Thank You guys! I've been trying and reading all your suggestions, and I've found and debugged it. Thanks to the one said that I need to check what message I can get in the catch.
Appreciated all your help.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
JOptionPane.showMessageDialog(null, "FOUND!");
}
else{
JOptionPane.showMessageDialog(null, "Not Found!");
}
}
}catch(SQLException exc){
JOptionPane.showMessageDialog(null, exc.getMessage());
}
ID Found!
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(); }
}
}
Well I was wondering if there is any other way to get data from a SQL Query.
What I mean is that the "main" code that I always find is
Connection con = (connect to db)
PreparedStatement st = con.prepareStatement(....);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
//do something
}
But if I want to retrieve specific data for example lets assume that my query is
Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("SELECT login,email FROM accounts WHERE login=?");
ps.setString(1, account);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
if (rs.getString("login").equals(account))
{
email = rs.getString("email");
break;
}
}
Is there any other way except that while loop to retrieve data?
The if condition inside the while loop is completely redundant - the where clause takes care of it and assures that any data returned from this query would have a login field that's equal to the value of account.
If you're sure there's no more than one row like this (e.g., the login column is a unique identifier in your table), you could just replace the while loop with an if:
// Check that such a logic exists
if (rs.next()) {
email = rs.getString("email");
}
// for good measures, just double check there isn't more than one
// of these logins:
if (rs.next()) {
throw new Exception ("This cannot be!"); // Or something more sensible
}