I have written a query as given below-
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
String fetchOneSQL = "select p.NAME from PAPER p where p.PAPERID="+paperId;
dbConnection = icrudResultAnalysis.getConnection();
preparedStatement = dbConnection.prepareStatement(fetchOneSQL);
rs = preparedStatement.executeQuery();
while (rs.next()) {
Paper paper=new Paper();
paper.setName(rs.getString(NAME));
}
// get new records list
preparedStatement=null;
rs=null;
String getListSql="select ib.NAME from ITEMBANK ib where ib.ITEMBANKID="+itemBankId;
preparedStatement = dbConnection.prepareStatement(getListSql);
rs = preparedStatement.executeQuery();
while (rs.next()) {
ItemBank itemBankObj=new ItemBank();
itemBankObj.setName(rs.getString(NAME));
listItemBanks.add(itemBankObj);
}
rs.close();
preparedStatement.close();
dbConnection.close();
} catch (Exception e) {
LOGGER.error("Exception Occured while fetching All record: "
+ e.getMessage());
} finally {
try{
if (rs!=null){
rs.close();
}
}catch(SQLException e)
{
LOGGER.error(RESULTSETCLOSEEXCEPTION + e.getMessage());
}
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (SQLException e) {
LOGGER.error(STATEMENTCLOSEEXCEPTION
+ e.getMessage());
}
try {
if (dbConnection != null) {
dbConnection.close();
}
} catch (SQLException e) {
LOGGER.error(CONNECTIONCLOSEEXCEPTION
+ e.getMessage());
}
}
In above code i have used single resultset for two select statement by creating ResulSet rs =null . Is it good practice? Or i have to close ResultSet each time? What is difference between closing ResultSet and making ResultSet null?
All resources MUST BE CLOSED after use using .close() method! And resultSet is not an exception, except in this case (from ResultSet javadoc):
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.
In your case you have to manual .close() the first opened resultset, but not necessary the second used; making a resultSet = null only set reference to variable resultSet equals null, no more no less.
If you are using Java7, Resultset is implementing AutoCloseable and you can use this feature to rewrite your code in cleaner way (look Oracle doc)
When you are re-using resources(resultSet,PrepareStatement),they must be closed first...Instead of setting prepare statement to NULL.You must close it and it will automatically close the result set.There is no need to explicitly close the result set.
Related
I am developing an application for my final year project, I need a quick clarification on java JDBC .. I am using Oracle physical connection(no connection pooling). When a user search in search criteria, the query execution is happening in 10 ms and returning the result set to UI is taking up to 1 minute. Code is been attached.
Connection con=null;
OracleConnection ocon = null;
ResultSet rs = null;
Gson gson = new Gson();
String gsonOrdrHeaderEntity="";
JSONObject searchObject = new JSONObject();
JSONObject returnSearchObject = new JSONObject();
CallableStatement callableStatement = null;
ArrayList<SearchEntity> searchArrayList = new ArrayList<>();
try{
con= DatasourceConfiguration.openConnection();
ocon = (OracleConnection)con.unwrap(OracleConnection.class);
callableStatement= con.prepareCall("call SEARCHPKG.QUERY(?,?,?,?,?)");
callableStatement.setString(1,entity.getSearch1());
callableStatement.setString(2,entity.getSearch2());
callableStatement.setString(3,entity.getSearch3());
callableStatement.setString(4,entity.getSearch4());
callableStatement.registerOutParameter(5, OracleTypes.CURSOR);
callableStatement.execute();
rs = ((OracleCallableStatement) callableStatement).getCursor(39);
if(rs != null)
while(rs.next()) {
OrderHeaderEntity searchEntity = new OrderHeaderEntity();
searchEntity.setSearch1(rs.getString(1));
searchEntity.setSearch2(rs.getString(3));
searchEntity.setSearch3(rs.getString(4));
searchEntity.setSearch4(rs.getString(5));
/**
* Description : Since there are will multiple order in a single search, we are adding the row to an array and iterating over it
*/
searchArrayList.add(searchEntity);
}
}catch(SQLException e){
logger.info("SQLException while performing search: "+e.getMessage());
throw e;
}catch(Exception e){
logger.info("Exception while performing search: "+e.getMessage());
}finally {
try {
if(rs != null) {rs.close();}
} catch (Exception e2) {
logger.info("Error while closing the search resultSet : "+e2.getMessage());
}
try {
if(callableStatement!=null) {callableStatement.close();}
} catch (Exception e2) {
logger.info("Error while closing the search callableStatment :"+e2.getMessage());
}
finally {
}
try {
if(con!=null) {con.close();}
} catch (Exception e2) {
logger.info("Error while the search connection :"+e2.getMessage());
}
}
}
/**
* #Description : mapping result set with JAVA object
*/
logger.info("Inside ProcedureCall >> search Proc>> converted to JSON successfully");
gsonOrdrHeaderEntity= gson.toJson(searchArrayList);
searchObject.put("order_header", gsonOrdrHeaderEntity);
returnSearchObject.put("status", "success");
returnSearchObject.put("message","Order Header Retrieved Successfully");
returnSearchObject.put("data", searchObject);
return returnSearchObject.toString();
public void createCostRecord() throws Exception
{
Context ctx = null;
Connection conn = null;
CallableStatement ps = null;
ResultSet rs = null;
boolean spReturn = false;
try{
ctx = new InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("CSMWebAppjndi");
conn = ds.getConnection();
conn.setAutoCommit(true);
String sp = "{call usp_CreateCostRecords(?,?)}";
ps = conn.prepareCall(sp);
ps.setInt(1, 1000);
ps.setInt(2, 2000);
for(int i=0;i<3;i++)
{
ps.executeQuery();
}
} catch (NamingException e)
{
log.error(e,e);
} catch (SQLException e)
{
log.error(e,e);
}
catch(Exception e)
{
log.error(e,e);
}
finally {
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn != null){
conn.close();
}
if(ctx != null ){
ctx.close();
}
}
}
while calling the above method the line number 23 executeQuery works fine for the first iteration of the for loop,
on second iteration of the for loop its getting struck at executeQuery and the procedure never completes execution.
But the weird thing is while i try the same procedure with same input from SQL developer its getting executed for any number of times without any struck.
Anyone help me to understand why the procedure from java is getting struck at second attempt and but its working fine in SQL developer.
I'm trying to get values from resulset, but it return nothing.
When i'm trying to do it through plain sql it return some values.
List<String> res = new ArrayList<String>();
try {
String query = "SELECT COLUMN_NAME FROM idoc.columns_to_show where user = ? "
+ DAO.DB2_UR_POSTFIX;
Connection connection = Properties.getDocsConnection();
try {
PreparedStatement pr = connection.prepareStatement(query);
try {
pr.setString(1, user.getDomainName());
ResultSet rs = pr.executeQuery();
try {
while (rs.next()) {
res.add(rs.getString("COLUMN_NAME"));
}
} finally {
rs.close();
}
} finally {
pr.close();
}
} finally {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return res;
Don't use column name "user" it is reserved name for DB2 database.
Therefore I couldn't find any result.
Hello everyone I'm trying to make a scheduling system for my System and Analysis Design thesis and I am having trouble trying to connect/bind/make the jTable listen to the jDateChooser's input. Elaborately, I want my scheduling to be like this:
I choose a date in the jDateChooser
jTable will 'sort out' itself via the date inputted on the jDatechooser
is there anyway to do this?
For now all I have is a table propertyChangelistener:
private void sched_tablePropertyChangeListener(java.beans.PropertyChangeEvent evt) {
try{
String calendar = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ?";
ps= conn.prepareStatement(query);
ps.setString(1, calendar);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null)
try { conn.close();
} catch (SQLException ignore) {}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
Somehow when I run my application it doesn't seem to open if that block of code is on it which means I really did do something wrong. Can anyone change or tell me what I should do or where should I start with the jTable listening to the jDatechooser thing?
~Thanks in advance for those who will answer!~
Nevermind, turns out all I had to do was change the jDateChooser's Date Format since it wasn't exactly the same formatting hence I couldn't call anything from the database. If anyone's interested on what I did I'll just leave this here
private void jdcPropertyChange(java.beans.PropertyChangeEvent evt) {
try{
String d1 = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ? order by time,timezone";
ps = conn.prepareStatement(query);
ps.setString(1, d1);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null) {
try { conn.close();
} catch (SQLException ignore) {}
}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
What this does is that everytime I pick on a date from the jDateChooser(named it jdc) the table/database calls that date and sorts it out. Which is what I wanted.
I'm trying to update a row in ResultSet, but it is throwing an error. I passed the constant value ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE to createStatement.
this is my code :
public void modifyPrice(float percentage) throws SQLException {
try {
con = util.connectdb();
con.setAutoCommit(false);
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select * from " + util.dbName
+ ".COFFEES");
while (rs.next()) {
float f = rs.getFloat("PRICE");
rs.updateFloat("PRICE", f * percentage);
rs.updateRow();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (st != null) {
st.close();
con.close();
}
}
}
When I executed this code block, the stack below got printed on console.
java.sql.SQLException: Invalid operation for read only resultset: updateFloat
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:131)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:197)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:261)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:269)
at oracle.jdbc.driver.BaseResultSet.updateFloat(BaseResultSet.java:236)
at oracle.jdbc.driver.OracleResultSet.updateFloat(OracleResultSet.java:677)
at tutorial.ModifyResultSet.modifyPrice(ModifyResultSet.java:29)
at tutorial.ModifyResultSet.main(ModifyResultSet.java:15)
Can anyone help me fix this error?
According to these links
http://www.coderanch.com/t/301466/JDBC/databases/Invalid-operation-read-only-resultset
http://www.coderanch.com/t/295932/JDBC/databases/updateXXX-function-ResultSet
instead of "select * from" you should use "select my_column_name from" statement.
See if it makes any difference.