I am getting this error when I run my code
Below is the code I have used:
String sql="SELECT * FROM PERSONS WHERE PERSONJOB='ADMIN'";
Statement stmt=null;
ResultSet rs=null;
try
{
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
While(rs.next())
{
String name=rs.getString(1);
long id=rs.getLong(2);
System.out.println(name);
System.out.println(id);
}
}
catch(Exception e)
{
throw e;
}
finally
{
rs.close();
stmt.close();
}
I want to reuse the connection, so I didn't close the connection.
After I closed the ResultSet and Statement, I am getting the "maximum open cursors exceeded" error.
Anyone please help me to solve this error.
My guess is that the close() of your ResultSet is failing, which would result in multiple open cursors and eventually hit the max configured open cursor count. Could you modify your code to:
Statement stmt = conn.createStatement();
try
{
ResultSet rs = stmt.executeQuery("SELECT * FROM PERSONS WHERE PERSONJOB = 'ADMIN'");
try
{
while ( rs.next() )
{
String name = rs.getString(1);
long id = rs.getLong(2);
System.out.println(name);
System.out.println(id);
}
}
finally
{
try
{
rs.close();
}
catch (Exception ignore) { }
}
}
finally
{
try
{
stmt.close();
}
catch (Exception ignore) { }
}
EDIT: will be good to also clean up the already opened cursors with a combination of:
SELECT oc.user_name, oc.sql_text, s.SID, s.SERIAL#
FROM v$open_cursor oc
, v$session s
WHERE oc.sid = s.sid
EXEC SYS.KILL_SESSION(xxx,xxxxx);
or restart the DB.
Related
I had a java app with mysql connection but i had to transfer my database to sqlite from mysql because of mysql can not be embedded, i have the connection but i get this exception when i am using the app.
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
I learnt this is a common mistake but i tried most of the answers however couldn't solve. The problem is i have about 30 different methods with void type or return types like these 2 for example below; (I call these methods on my swing app later)
I have these at start of my class;
private Connection con = null;
private Statement statement = null;
private PreparedStatement preparedstatement = null;
Methods for example;
public int lastPlaceProgram(){
String query= "Select * from userprogram where laststayed = 1";
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
int programid = 0;
while(rs.next()){
programid = rs.getInt("programid");
}
return programid;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return 0;
}
}
or
public String programType(int programid){
String query = "Select * from programs where id = ?";
try {
preparedStatement = con.prepareStatement(query);
preparedStatement.setInt(1, programid);
ResultSet rs = preparedStatement.executeQuery();
String type = "";
while(rs.next()){
type = rs.getString("type");
}
return type;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
And constructor;
public Operations() {
String url = "jdbc:sqlite:C://Users//Me//Desktop//sqlited/trying.db";
try {
con = DriverManager.getConnection(url);
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
}
}
I tried to add these finally block to after catch blocks of all my 30 methods;
finally{
try{
con.close();
} catch(Exception e){
}
}
But it didn't work, it gave Connection is closed mistake this time. I also tried to add preparedstatement.close(); to this finally block but didn't still work.
Finally blocks didn't work for me, i closed them manually if i had that variable to close. I mean if i used ResultSet and PreparedStatement at a method then i made rs.close() and preparedstatement.close() just before catch or before return. If i just had Preparedstatement variable on the method then i just did preparedstatement.close() before catch block or before return.
I've encountered an some inconsistencies regarding the results from an SQL query.
Here is the query which I'm using as a prepared statement.
delete ROLE_USER_MAP
from ROLE_USER_MAP inner join ROLE_MANAGER on ROLE_USER_MAP.R_ID=ROLE_MANAGER.R_ID
where ROLE_USER_MAP.U_ID= ? and ROLE_MANAGER.M_ID= ?
Here is how I calling the prepared statement in my Java application.
public void deleteRoles(String mID, String uID) throws OperationFailedException
{
Connection conn = null;
try
{
conn = this.getConnection();
this.deleteRoles(mID, uID, conn);
}
catch (Exception e)
{
AdminLogger.error(this.getClass(), e);
throw new OperationFailedException("Failed to remove roles for user.");
}
finally
{
try
{
conn.close();
}
catch (Exception e)
{
}
}
}
private void deleteRoles(String mID, String uID, Connection conn) throws SQLException
{
PreparedStatement stmt = null;
try
{
stmt = *retrieving ps*
stmt.setString(1, uID);
stmt.setString(2, mID);
int i = stmt.executeUpdate(); // returns 1 here
if (i < 1)
{
throw new SQLException("Failed to remove roles for user.");
}
} finally
{
stmt.close();
}
}
It runs fine locally and in SSMS with all rows fitting the where clause being deleted but when I try to deploy it to my hosted server, only the first row in the table is being deleted.
Can anyone help me with this?
Thanks in advance.
What I did wrong? I tried to swap rs.close(), pstmt.close(), conn.close().
I created a PreparedStatement.
But I still can not display the contents of a database table. If I remove conn.close(), everything works! How close the connection and get an output on the jsp?
This is my code:
public ResultSet executeFetchQuery(String sql) {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = Database.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(PhoneDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
return rs;
}
public ArrayList<Phone> getAllPhone() {
ArrayList<Phone> list = new ArrayList<>();
String sql = "SELECT * FROM phones.product;";
ResultSet rs = executeFetchQuery(sql);
try {
while (rs.next()) {
Phone phone = new Phone();
phone.setId(rs.getInt("id"));
phone.setName(rs.getString("name"));
phone.setPrice(rs.getInt("price"));
phone.setQuantity(rs.getInt("quantity"));
phone.setDescription(rs.getString("description"));
System.err.println(phone);
list.add(phone);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
return list;
}
ResultSet rs = executeFetchQuery(sql);
The above statement closes everything.
Actually your code should be
DBConnection
Iterate through result set
Store the values/display the value directly(depends on your need)
Finally close the connection.
Which is the proper way to access the data from db.
The more common pattern for this kind of process is to maintain the connection and the statement outside the main query code. This is priomarily because connections would generally be allocated from a pool as they are expensive to create and preparing the same statement more than once is wasteful.
Something like this is most likely to work both efficiently and correctly.
static final Connection conn = Database.getConnection();
static final String sql = "SELECT * FROM phones.product;";
static final PreparedStatement pstmt = conn.prepareStatement(sql);
public ArrayList<Phone> getAllPhone() {
ArrayList<Phone> list = new ArrayList<>();
ResultSet rs = pstmt.executeQuery();
try {
while (rs.next()) {
Phone phone = new Phone();
phone.setId(rs.getInt("id"));
phone.setName(rs.getString("name"));
phone.setPrice(rs.getInt("price"));
phone.setQuantity(rs.getInt("quantity"));
phone.setDescription(rs.getString("description"));
System.err.println(phone);
list.add(phone);
}
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
rs.close();
}
return list;
}
Note how the ResultSet is closed in a finally block to stop leaks.
There are variations of this pattern which, for example, only create the connection and prepare the statement at the last minute rather than as static final fields like I have here.
private void btn_nextActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect =DriverManager.getConnection("jdbc:odbc:reimbursement");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
try
{
stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
sql = "select * from reimbursementMaster";
rs = stmt.executeQuery( sql );
rs=stmt.getResultSet();
if(rs.next())
{
empcode=rs.getString("EmployeeCode");
empname=rs.getString("EmployeeName");
loc=rs.getString("Location");
location=loc;
}
else
{
rs.previous();
JOptionPane.showMessageDialog(this, "End of File","Message",JOptionPane.INFORMATION_MESSAGE );
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
Let me guess...
Your problem is you are getting only the first result all the times is because the resultset is reopened from scratch every time you press the next button.
declare Resultset rs as class member,
open rs out of btn_nextActionPerformed() (where you build the UI
can be a good place) and rs.next() should work as expected.
There are many steps involved in executing one SQL statement in Java:
Create connection
Create statement
Execute statement, create resultset
Close resultset
Close statement
Close connection
At each of these steps SQLException can be thrown. If we to handle all exception and release all the resources correctly, the code will will look like this with 4 levels of TRY stacked on the top of each other.
try {
Connection connection = dataSource.getConnection();
try {
PreparedStatement statement = connection.prepareStatement("SELECT 1 FROM myTable");
try {
ResultSet result = statement.executeQuery();
try {
if (result.next()) {
Integer theOne = result.getInt(1);
}
}
finally {
result.close();
}
}
finally {
statement.close();
}
}
finally {
connection.close();
}
}
catch (SQLException e) {
// Handle exception
}
Can you propose a better (shorter) way to execute a statement while still release all the consumed resources?
If you are using Java 7, the try with resources statement will shorten this quite a bit, and make it more maintainable:
try (Connection conn = ds.getConnection(); PreparedStatement ps = conn.prepareStatement(queryString); ResultSet rs = ps.execute()) {
} catch (SQLException e) {
//Log the error somehow
}
Note that closing the connection closes all associated Statements and ResultSets.
Check out Apache Commons DbUtils, and in particular the closeQuietly() method. It will handle the connection/statement/result set closing correctly, including the cases where one or more are null.
An alternative is Spring JdbcTemplate, which abstracts a lot of work away from you, and you handle your database queries in a much more functional fashion. You simply provide a class as a callback to be called on for every row of a ResultSet. It'll handle iteration, exception handling and the correct closing of resources.
I create a utility class with static methods I can call:
package persistence;
// add imports.
public final class DatabaseUtils {
// similar for the others Connection and Statement
public static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
LOGGER.error("Failed to close ResultSet", e);
}
}
}
So your code would be:
Integer theOne = null;
Connection connection = null;
PreparedStatement statment = null;
ResultSet result = null;
try {
connection = dataSource.getConnection();
statement = connection.prepareStatement("SELECT 1 FROM myTable");
result = statement.executeQuery();
while (result.next()) {
theOne = result.getInt(1);
}
} catch (SQLException e) {
// do something
} finally {
DatabaseUtils.close(result);
DatabaseUtils.close(statement);
DatabaseUtils.close(connection);
}
return theOne;
I'd recommend instantiating the Connection outside this method and passing it in. You can handle transactions better that way.
Connection connection = null;
PreparedStatement statement = null;
ResultSet result = null;
try {
connection = dataSource.getConnection();
statement = connection.prepareStatement("SELECT 1 FROM myTable");
result = statement.executeQuery();
if (result.next()) {
Integer theOne = result.getInt(1);
}
}
catch (SQLException e) { /* log error */ }
finally {
if (result != null) try { result.close(); } catch (Exception e) {/*log error or ignore*/}
if (statement != null) try { statement.close(); } catch (Exception e) {/*log error or ignore*/}
if (connection != null) try { connection.close(); } catch (Exception e) {/*log error or ignore*/}
}
Just close the Connection, this releases all resources*. You don't need to close Statement and ResultSet.
*just make sure you don't have any active transactions.
Your code can be shortened and written in this way...
Connection connection = dataSource.getConnection();
PreparedStatement statement = null;
ResultSet result = null;
try {
statement= connection.prepareStatement("SELECT 1 FROM myTable");
result = statement.executeQuery();
if (result.next()) {
Integer theOne = result.getInt(1);
}
} catch (SQLException e) {
// Handle exception
} finally {
if(result != null) result.close();
if(statement != null) statement.close();
if(connection != null) connection.close();
}