This question already has answers here:
SQLException: Exhausted Resultset
(3 answers)
Closed 7 years ago.
i have problem with the below code. help me!!
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:xe","system","**********");
Statement st=conn.createStatement();
String sql="select password from db where username='user'";
ResultSet rs=st.executeQuery(sql);
rs.next();
String password=rs.getString("password");
if(password.equals(pass))
{
RequestDispatcher rd=req.getRequestDispatcher("/home.jsp");
rd.forward(req,res);
}
else
{
out.println("invalid username and password");
}
when i execute this code i am getting an java sql exception : exhausted result set. thanks in advance...
Instead of using rs.next();, use it with while e.g while(rs.next()). Once you got the resultset, the pointer will point to the first record. Each time you do a rs.next(), the pointer will advances to the next record. If you use with while, once you reach to the end of your resultset, rs.next() will return false once all records are iterated. In your case, since you are not checking whether resultset has exhausted and trying to advanced the pointer, you are getting the exception.
That is correct, because if you enter wrong username or password, NO record will be returned. So, when you use the rs.next(); in this case, it is trying to access the first row of the empty result set
String password=rs.getString("password");//error, if rs is empty
in the where clause you are not using user variable
where clause should be where username='"+user+"'";
and
instead of
rs.next();
use
if(rs.next())
{
String password=rs.getString("password");
........
}
Related
This question already has answers here:
ResultSet: Exception: set type is TYPE_FORWARD_ONLY -- why?
(9 answers)
Closed 20 days ago.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/onlineshop?autoReconnect=true&useSSL=false","root",DatabaseConnection.root);
PreparedStatement ps=con.prepareStatement("select * from custinfo");
ResultSet rs=ps.executeQuery();
/*******
//for counting the number of rows in result set
if(rs.last()) {
x=rs.getRow();
rs.beforeFirst();
}
When I'm trying to execute it it showing me the error:
java.sql.SQLException: Operation not allowed for a result set of type
ResultSet.TYPE_FORWARD_ONLY.
Can you help me how can I solve this?
The error message says it all - the ResultSet is of TYPE_FORWARD_ONLY, so you can't scroll it back with beforeFirst(). Having said that, querying the entire table (and having to send all that data from the database to your application) just to get its size is probably not a good practice. It would be much easier to use an aggregate query to get the number of rows:
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlineshop?autoReconnect=true&useSSL=false","root",DatabaseConnection.root);
PreparedStatement ps = con.prepareStatement("select count(*) from custinfo");
ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
size = rs.getInt(1);
}
}
This question already has answers here:
Getting java.sql.SQLException: Operation not allowed after ResultSet closed
(2 answers)
Closed 7 years ago.
What I know-we cannot call ResultSet after this has been closed.and this is a good practice to close every ResultSet,StatementandConnection after using this.
But in my code I never closed connection then why there is-
java.sql.SQLException: Operation not allowed after ResultSet closed
my code is as follows:
Edited-
try{
Connection con=CommonUtil.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from logirecord");
int flag=0;
while(rs.next()){
if(rs.getString(2).trim().equals(username)&&rs.getString(3).trim().equals(password)){
flag=1;
ResultSet rs1=st.executeQuery("select * from personrecord where LoginId='"+ rs.getString(1).trim()+"'");
if(rs1.next()){
String name=rs1.getString(1);
String address=rs1.getString(2);
String hobby=rs1.getString(4);
}
//Exception here.
ResultSet rs2=st.executeQuery("select * from interest where LoginId='"+rs.getString(1).trim()+"'");
//at com.org.test.LoginServlet.doPost(LoginServlet.java:49)
if(rs2.next()){
String interest=rs2.getString(2);
String interest2=rs2.getString(3);
String interest3=rs2.getString(4);
}
request.getRequestDispatcher("display.jsp").forward(request, response);
return;
}
}
}catch(Exception e){
e.printStackTrace();
}
You have several ResultSet pertaining to the same Statement object concurrently opened. (see here - http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html):
By default, only one ResultSet object per Statement object can be open
at the same time. Therefore, if the reading of one ResultSet object is
interleaved with the reading of another, each must have been generated
by different Statement objects. All execution methods in the Statement
interface implicitly close a statment's current ResultSet object if an
open one exists.
And you are not closing rs that make it more worst.
Well you are getting
java.sql.SQLException: Operation not allowed after ResultSet closed
Because you are trying to traverse a result set while traversing another result set of same connection.
If you're nesting the processing of two result sets from the same database, you're doing something wrong. The combination of those sets should be done on the database side.
This question already has answers here:
Cannot issue data manipulation statements with executeQuery()
(11 answers)
Closed 7 years ago.
I am having a problem with an MySQL Update query. Here is the code:
String s2="foo";
String s6="bar";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root");
String query="update mydb set Status='"+s6+"' where IC_Number='"+s2+"'";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(query);
con.close();
}
catch(Exception e)
{
System.out.println("Error in login:"+e);
}
}
}
I get the error
can not issue data manipulation statements with executeQuery().
Can anyone point out where the problem is ?
For update operation you have to use executeUpdate which returns an integer but not a ResultSet
Change:
ResultSet rs=stmt.executeQuery(query);
To:
int updateResult = stmt.executeUpdate( query );
Documentation:
java.sql.Statement.executeUpdate(java.lang.String)
Executes the given SQL statement, which may be an INSERT, UPDATE, or
DELETE statement or an SQL statement that returns nothing, such as an
SQL DDL statement.
You should use executeUpdate() instead of executeQuery();
public UserBean authenticate(String username,String password){
PostGresDAO pg=new PostGresDAO(); //creates new connection
Connection conn=pg.getConnecion(); //return connection object
PreparedStatement ps;
ResultSet rs;
String query="select password,name from scg_users where username=?";
UserBean ub=null;
boolean authenticated=false;
try{
ps=conn.prepareStatement(query);
ps.setString(1, username);
rs=ps.executeQuery();
if(rs!=null){
authenticated=password.equals(rs.getString(1)); //exception raised here
if(authenticated){
ub=new UserBean();
ub.setUser(rs.getString(2));
ub.setUsername(username);
}
}
}
catch(SQLException e){
e.printStackTrace();
}
return ub;
}
I am using this code for authenticating a user. The username and password are extracted from the request parameter and passed onto this method for authentication. But it throws a:
org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.
Please advice.
The error is telling you exactly what's wrong - you're not calling next() on your ResultSet to get to the first row of the results.
This line:
if(rs!=null)
is pointless as far as I know; I don't believe executeQuery will ever return null. If there's a problem in your query, an exception will be thrown. If there are no results, it will return an empty result set. To see if there's a row, you should call next() and check the return value:
if (rs.next())
Additionally:
Catching an exception and just printing the stack trace without rethrowing is almost always the wrong approach
Your code suggests that you're storing passwords in plain text. Please don't. Really, really don't.
Because I got the message even when I called next() on resultSet I'll tell my solution.
The solution is NOT to call resultSet.get* on your resultSet if it's empty. So do a check if(resultSet.next()){ ...
Instead of
if(rs!=null)
You need to check for
if(rs.next())
This will return the first row, if there are any matching rows.
Maybe you have resultSet.next() in debugger Inline Watches :)
It was the case for me;
So my check if (resultSet.next()) returns true but when I go inside the if block, the next() is called again and then there is no data so I got the same error message
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to get the insert ID in JDBC?
Hi, I'm using JDBC to connect on database through out Java.
Now, I do some insert query, and I need to get the id of last inserted value (so, after a stmt.executeUpdate).
I don't need something like SELECT id FROM table ORDER BY id DESC LIMIT 1, because I may have concurrency problems.
I Just need to retrieve the id associated to the last insertion (about my instance of the Statement).
I tried this, but seems it doesn't work on JDBC :
public Integer insertQueryGetId(String query) {
Integer numero=0;
Integer risultato=-1;
try {
Statement stmt = db.createStatement();
numero = stmt.executeUpdate(query);
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getInt(1);
}
rs.close();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
errore = e.getMessage();
risultato=-1;
}
return risultato;
}
In fact, every time risultato = -1, and I get java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().
How can I fix this problem? Thanks Stackoverflow People :)
Wouldn't you just change:
numero = stmt.executeUpdate(query);
to:
numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
Take a look at the documentation for the JDBC Statement interface.
Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.
Alternatively you can do:
Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getString(1);
}
But use Sean Bright's answer instead for your scenario.