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();
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:
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");
........
}
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:
mysql prepared statement error: MySQLSyntaxErrorException
(2 answers)
Closed 8 years ago.
I've spent hours looking at what seems like what should be perfectly working code. The connection.createStatement() version of this method works fine but as soon as I try to convert it over to the better, connection.prepareStatement() version it throws a MySQLSyntaxErrorException and complains about a problem near the '?' character in my query string. The code is posted below and I simply cannot see the problem with it. The database field is VARCHAR and accepts Strings so that is not the problem.
public Discussion getDbDiscussionInstance(String _instanceId) throws SQLException {
String qryStr = null;
PreparedStatement myStmt = null;
ResultSet myRs = null;
// Try to build the object with existing data.
try {
qryStr = "SELECT assignment_id, discussion_id, section_id, user_id, circle_id, breakout_id, title, description, created, due FROM macb_discussions WHERE instance_id=?";
myStmt = connection.prepareStatement(qryStr);
myStmt.setString(1, _instanceId);
myRs = myStmt.executeQuery(qryStr);
if (rs.next()) {
this.discussionId = myRs.getString("discussion_id");
}
} catch (SQLException e) {
dbFunc.catchSQLException(e);
} finally {
myRs.close();
myStmt.close();
}
}
Use only myStmt.executeQuery(); without the argument, you have already preperad the statement
From the docs,
Statement.executeQuery(String sql)
PreparedStatement.executeQuery()
So change your function accordingly.
myStmt = connection.prepareStatement(qryStr); to
myStmt = connection.prepareStatement();
This question already has answers here:
java.sql.SQLException: - ORA-01000: maximum open cursors exceeded
(14 answers)
Closed 9 years ago.
I've done connection to Oracle Database.
Now I'm facing
ORA-01000: maximum open cursors exceeded
I used code to insert data:
public static void OracleJDBC(String Serial_Number, String Charged_MDN) {
String dataInsertQuery = "insert into CDR_Huawei (Serial_Number, Charged_MDN) values ('" + Serial_Number + "', '" + Charged_MDN + "')";
String dataSelectQuery = "select * from CDR_Huawei";
Statement statement = null;
try {
statement = connection.createStatement();
statement.execute(dataInsertQuery);
//System.out.println("Data Inserted Successfully");
} catch (SQLException e) {
e.printStackTrace();
}
}
It works only for first 500 records, then I have the error Ora-1000.
I have about 6000 records in total.
I found some topics saying that configuration should be changed, but I can't change configuration.
Is there another way to solve this error?
Close your statement in a finally block.
try {
statement = connection.createStatement();
statement.execute(dataInsertQuery);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (statement != null) statement.close();
}
Every time new statement object is generated while you write
statement = connection.createStatement()
It is good practice to close the statement after using it...
statement.close(); after `statement.execute(dataInsertQuery);`
will solve your problem.
An extra answer to draw attention to ppeterka's comment:
You really should be using PreparedStatements here. The reason is that you are currently sending 6000 unique SQL insert statements to the database. The statements are unique because the values of the insert statements are glued in your statement text. The database will have to parse each unique statement and place it in its shared pool for reuse. But it won't reuse, since they are unique.
Using PreparedStatements where you bind in the values, you'll create only one unique SQL insert statement, which only needs to parse once and won't clutter the shared pool. Your database administrator will thank you for it.