I have this java function that runs and produces an error. I cannot figure out why this is occurring because this is the first function in the program to run so no other connections, statements, or result sets have been opened. The error is
Operation not allowed after ResultSet closed
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:768)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7008)
at equipmentinventoryimporter.Importer.sqlTable(Importer.java:219)
at equipmentinventoryimporter.Importer.main(Importer.java:58)
and the function is
private static void sqlTable(SQLTableJob sqltableJob) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connMySQL2 = null;
Statement stntMySQL2 = null;
try {
connMySQL2 = DriverManager.getConnection(mysqlAddress, mysqlUsername, mysqlPassword);
stntMySQL2 = connMySQL2.createStatement();
//MySQL Transaction
System.out.println("Starting " + sqltableJob.getMysqlTable() + " transaction");
stntMySQL2.execute("START TRANSACTION");
String insertQuery = "";
try {
final String inactiveQuery = "UPDATE `" + sqltableJob.getMysqlSchema() + "`.`" + sqltableJob.getMysqlTable() + "` SET `active`=0";
stntMySQL2.executeUpdate(inactiveQuery);
final ResultSet rs2 = stntMySQL2.executeQuery(sqltableJob.getSQLSelectQuery());
int counter = 0;
while (rs2.next()) {
counter++;
final String mysqlSetClause = sqltableJob.getMysqlSetClause(rs2);
insertQuery = "INSERT INTO `" + sqltableJob.getMysqlSchema() + "`.`" + sqltableJob.getMysqlTable() + "` SET " +
mysqlSetClause +
" ON DUPLICATE KEY UPDATE " +
mysqlSetClause;
stntMySQL2.executeUpdate(insertQuery);
if (counter % 5000 == 0) {
System.out.println("Processed " + counter + " rows.");
}
}
rs2.close();
if (!sqltableJob.isKeepInactives()) {
final String deleteQuery = "DELETE FROM `" + sqltableJob.getMysqlSchema() + "`.`" + sqltableJob.getMysqlTable() + "`" +
"WHERE `active`=0";
stntMySQL2.executeUpdate(deleteQuery);
}
stntMySQL2.execute("COMMIT");//last line of try block
System.out.println("Committed " + sqltableJob.getMysqlTable() + " transaction");
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.out.println("Transaction level exception thrown.");
System.out.println(insertQuery);
stntMySQL2.execute("ROLLBACK");
System.out.println("MySQL query rolled back.");
}
//Another MySQL Transaction goes here
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.out.println("Connection level exception thrown.");
} finally {
if (stntMySQL2 != null) {
try {
stntMySQL2.close();
} catch (Exception ex) {
}
}
if (connMySQL2 != null) {
try {
connMySQL2.close();
} catch (Exception ex) {
}
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.out.println("Program level exception thrown.");
}
}
SQLTableJob is
package equipmentinventoryimporter;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* #author jmgreen
*/
public interface SQLTableJob {
public String getMysqlSchema();
public String getMysqlTable();
public String getSQLSelectQuery();
public String getMysqlSetClause(ResultSet rs) throws SQLException;
public boolean isKeepInactives();
}
and the specific SQLTableJob being referenced is
public class SQLTableJob10I implements SQLTableJob{
public boolean isKeepInactives() {
return true;
}
public String getMysqlSchema() {
return "Temp_Equipment_Inventory";
}
public String getMysqlTable() {
return "PC_Combined";
}
public String getSQLSelectQuery() {
final String sqlSelectQuery = "SELECT *" +
" FROM Temp_Equipment_Inventory.PC_Table10i";
return sqlSelectQuery;
}
public String getMysqlSetClause(ResultSet rs) throws SQLException {
final String mysqlSetClause =
"`Account_No`=" + Importer.sqlChar(rs.getString("Account_No")) +
",`Inventory_No`=" + Importer.sqlChar(rs.getString("Inventory_No")) +
",`Building_No`=" + Importer.sqlChar(rs.getString("Building_No")) +
",`Location`=" + Importer.sqlChar(rs.getString("Location")) +
",`FYYR_No`=" + Importer.sqlChar(rs.getString("FYYR_No")) +
",`Cost`=" + Importer.sqlChar(rs.getString("Cost")) +
",`Name`=" + Importer.sqlChar(rs.getString("Name")) +
",`Desc1`= ''" +
",`Desc2`= ''" +
",`Desc3`= ''" +
",`CDCATY`=" + Importer.sqlChar(rs.getString("CDCATY")) +
",`CDSRCE`=" + Importer.sqlChar(rs.getString("CDSRCE")) +
",`FLDCAL`=" + Importer.sqlChar(rs.getString("FLDCAL")) +
",`CDACQN`=" + Importer.sqlChar(rs.getString("CDACQN")) +
",`FLOWNR`=" + Importer.sqlChar(rs.getString("FLOWNR")) +
",`FLSHAR`=" + Importer.sqlChar(rs.getString("FLSHAR")) +
",`CDDELT`=" + Importer.sqlChar(rs.getString("CDDELT")) +
",`CNYTDT`=" + Importer.sqlChar(rs.getString("CNYTDT")) +
",`NOPURO`=" + Importer.sqlChar(rs.getString("NOPURO")) +
",`NOPIMO`=" + Importer.sqlChar(rs.getString("NOPIMO")) +
",`CDPREI`=" + Importer.sqlChar(rs.getString("CDPREI")) +
",`Original_Amount`=" + Importer.sqlChar(rs.getString("Original_Amount")) +
",`Serial_Code`=" + Importer.sqlChar(rs.getString("Serial_Code")) +
",`CDCOMP`=" + Importer.sqlChar(rs.getString("CDCOMP")) +
",`NOCHECK`=" + Importer.sqlChar(rs.getString("NOCHECK")) +
",`CDCOMM`=" + Importer.sqlChar(rs.getString("CDCOMM")) +
",`Last_Update`=" + Importer.sqlDate(rs.getString("Last_Update")) +
",`CDDEPT`=" + Importer.sqlChar(rs.getString("CDDEPT")) +
",`Room_No`=" + Importer.sqlChar(rs.getString("Room_No")) +
",`Date_Scanned`=" + Importer.sqlDate(rs.getString("Date_Scanned")) +
",`Date_Acquired`=" + Importer.sqlDate(rs.getString("Date_Acquired")) +
",`Manufacturer_Name`=" + Importer.sqlChar(rs.getString("Manufacturer_Name")) +
",`Expiry_Date`=" + Importer.sqlDate(rs.getString("Expiry_Date")) +
",`Active`='1'";
return mysqlSetClause;
}
}
From the 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.
From your code:
stntMySQL2.executeUpdate(inactiveQuery);
final ResultSet rs2 = stntMySQL2.executeQuery(sqltableJob.getSQLSelectQuery());
while (rs2.next()) {
...
stntMySQL2.executeUpdate(insertQuery);
You are re-executing stntMySQL2 inside the loop. This automatically closes rs2.
To fix, use a different statement object inside the loop.
Related
How can I only make my application execute the changes to a database at the end of the while cycle?
I have this rollback method but I only the changes to be made to the database at the end of it because of inconsistent data handling
I have tried to set auto commit to false but even though the exception was thrown at the second iteration of the while cycle, the changes were still in the database(until the point before the interruption, the tables after that didn't suffer changes).
Am I doing something wrong?
#Override
public void rollback(Database database) throws CustomChangeException {
JdbcConnection connection = (JdbcConnection) database.getConnection();
try {
connection.setAutoCommit(false);
ResultSet rs = getTables(connection);
//if the user chose to use a suffix
if (this.getSuffix() != null) {
while (rs.next()) {
String tableName = rs.getString(3);
if (tableName.endsWith(this.getSuffix())) {
if (!checkColumnsExists(connection, tableName, newName)) {
throw new CustomChangeException("The column " + newName + " doesn't exist in the table " + tableName + " anymore.Please fix this");
}
PreparedStatement s = connection.prepareStatement(getRollbackQuery(tableName));
s.executeUpdate();
logger.info("Column name reversed to " + this.getColumnName() + " in table" + tableName);
}
}
}
//if the user chose to use a regex
if (this.getRegex() != null) {
Pattern pattern = Pattern.compile(this.getRegex());
while (rs.next()) {
String tableName = rs.getString(3);
Matcher matcher = pattern.matcher(tableName);
boolean matches = matcher.matches();
if (matches) {
if (!checkColumnsExists(connection, tableName, newName)) {
logger.error("The column " + newName + " doesn't exist in the table " + tableName + " anymore.Please fix this");
throw new CustomChangeException();
}
PreparedStatement s = connection.prepareStatement(getRollbackQuery(tableName));
s.executeUpdate();
logger.info("Column name reversed to " + this.getColumnName() + " in table" + tableName);
}
}
}
connection.commit();
} catch (SQLException | DatabaseException | DifferentDataTypeException e) {
logger.error(e.getMessage());
throw new CustomChangeException();
}
}
protected void saveData() {
Map<String, String> allStationsParams = new HashMap<>();
List<String> stations = getAllStations();
stmt = Database.getUpdateableStatement();
today = (SysTime.currentTimeMillis() / DasStamp.TICKS_PER_DAY) *
DasStamp.TICKS_PER_DAY;
String changeTimestamp = DasStamp.asCompactString(today);
String keyName = "COM.MAPPINGTOOLTIP." + attributeValue;
for (int row = 0; row < this.getTableModel().getRowCount(); row++) {
String station = (String)this.getTableModel().getValueAt(row, 0);
putInStationParams(this, station, allStationsParams, row);
}
for (String station : stations) {
boolean sendToDB = false;
try (ResultSet rs = this.rsParameters) {
rs.beforeFirst();
while (rs.next()) {
if (rs.getString("station").equals(station)) {
sendToDB = true;
break;
}
}
if (sendToDB) {
if (!rs.getString("value_text").equals(allStationsParams.get(station)) || !allStationsParams.containsKey(station)) {
sendToDB = true;
} else {
sendToDB = false;
}
} else if (allStationsParams.containsKey(station)) {
sendToDB = true;
}
if (sendToDB) {
String sql = "REPLACE INTO dss_parameter (key_name, station, valid_from, value_text"
+ ", change_timestamp) VALUES ('"
+ keyName + "','" + station + "','" + DasStamp.asDateOnlyString(today) + "','"
+ Helper.nz(allStationsParams.get(station)) + "','"
+ changeTimestamp + "') ;";
if (null != stmt) {
stmt.execute(sql);
if (!isResultSetEmpty(rs) && !rs.isAfterLast()) {
AdminLogger.log("dss_parameter", Action.UPDATE,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"value_text='" + rs.getString("value_text") + "'",
"value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
} else {
AdminLogger.log("dss_parameter", Action.INSERT,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"", "value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
}
}
}
} catch (SQLException e) {
AppFrame.msgBox("Error on insert: " + e.getMessage());
Helper.printMessage(true, false, "Parameter save failed!!", e);
}
}
}
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
Your rsParameters parameter is of Type Resultset.
In first iteration, after try{} block is complete close() method of rsParameters:ResultSet is called.
This internally makes all the properties of resultSet NUll.
That is the reason for getting Null properties during second iteration.
SEE: http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.27/com/mysql/jdbc/ResultSetImpl.java#ResultSetImpl.realClose%28boolean%29
My problem is that when I fire a query directly into Oracle, it returns me the rows with proper data. But when I try to fire the same query via Statement, its fetching me a resultset with no rows.
My code is as follows :
public void sendSMStoMobile() {
if (smsGatewayStatus.equals("STOPPED")) {
stringBuilder.append("The control is returning" + "\n");
jTextArea1.setText(stringBuilder.toString());
return;
}
DBCP dbcp = DBCP.getInstance(database_url, username, password);
Connection connection = null;
Statement statement = null;
try {
connection = dbcp.getConnection();
statement = connection.createStatement();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Message : " + ex.getMessage());
} catch (InterruptedException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Message : " + ex.getMessage());
}
ResultSet resultSet = null;
try {
sql = new StringBuffer();
sql.append("SELECT SMS_ID, MOBILE_NO, SMS_CONTENT ");
sql.append("FROM SMSDATA.SMS_DATA ");
//sql.append("WHERE SENT_STATUS = 'N' AND Message_Code IN('LOANREPAY') " );
//sql.append("WHERE SENT_STATUS = 'N' AND Message_Code IN('SPECIAL') " );
sql.append("WHERE SENT_STATUS = 'N' ");
//sql.append("WHERE tranum <= (select max(tranum) -25 from smsgtway.sms_all_tran where SENT_STATUS = 'N' AND Message_Code IN('MEMDEP','MEMGRANT','SAMGRANT')) and SENT_STATUS = 'N' AND Message_Code IN('MEMDEP','MEMGRANT','SAMGRANT') " );
sql.append("ORDER BY SMS_ID desc ");
// sql.append("ORDER BY SENT_TIMSTAMP " );
// For Test
//sql.append("SELECT customer_Code,MOBILE_NO, SMS_CONTENT,SMS_ID " );
//sql.append("FROM MB_SMS_DTL ");
//sql.append("WHERE SENT_STATUS = 'N' ");
//sql.append("ORDER BY SMS_ID " );
// End Test
resultSet = statement.executeQuery(sql.toString());
System.out.println("Code comes here");
/* if(!resultSet.next()){
stringBuilder.append("No Data Found" +"\n");
jTextArea1.setText(stringBuilder.toString());
} */
if (!resultSet.next()) {
System.out.println("no data");
} else {
System.out.println("Data Found...");
do {
//statement(s)
} while (resultSet.next());
}
while (resultSet.next()) {
System.out.println("Data Found...");
String smsId = resultSet.getString(1);
String destMobileNo = resultSet.getString(2);
String message = resultSet.getString(3);
OutboundMessage sms = new OutboundMessage(destMobileNo, message);
System.out.println("Code comes here" + smsId);
//System.out.println("sms = " + sms);
try {
Service.getInstance().sendMessage(sms);
} catch (TimeoutException timeoutException) {
System.out.println("1");
stringBuilder.append("Exception : " + timeoutException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (GatewayException gatewayException) {
System.out.println("2");
stringBuilder.append("Exception : " + gatewayException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (IOException iOException) {
System.out.println("3");
stringBuilder.append("Exception : " + iOException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (InterruptedException interruptedException) {
System.out.println("4");
stringBuilder.append("Exception : " + interruptedException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (java.lang.StringIndexOutOfBoundsException siobe) {
System.out.println("5");
stringBuilder.append("Exception : " + siobe.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
}
//Update Table After Send Message
String updateQuery = "UPDATE SMSDATA.SMS_DATA SET SENT_STATUS = 'Y', SENT_DATE = sysdate WHERE SMS_ID = " + smsId;
//String updateQuery = "UPDATE MB_SMS_DTL SET SENT_STATUS = 'Y' WHERE SMS_ID = " + tranNumber ;
//System.out.println("Update Query: " + updateQuery);
if (i < 10) {
System.out.print(smsId + ": Y, ");
}
if (i == 10) {
System.out.print(smsId + ": Y, " + "\n");
i = 0;
}
statement.executeUpdate(updateQuery);
connection.commit();
i = i + 1;
}
} catch (Exception e) {
System.out.println("Message: " + e.getMessage());
System.out.println("Cause: " + e.getCause());
stringBuilder.append("Message: " + e.getMessage() + "\n");
stringBuilder.append("Cause: " + e.getCause() + "\n");
jTextArea1.setText(stringBuilder.toString());
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
dbcp.releaseConnection(connection);
//Service.getInstance().stopService();
}
}
When I call this function , "no data" is printed in Console . The sql is correct . When I run the sql in Toad , I have found 2 rows .
Please help me .
I've created a derby Embedded Database in my eclipse project, and it runs well on eclipse, but when packing the project in Runnable jar file, it fails in connecting the database.
I've done something similar to this video
http://vinayakgarg.wordpress.com/2012/03/07/packaging-java-application-with-apache-derby-as-jar-executable-using-eclipse/
Here is my Communicate.java
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Communicate {
private static final String dbURL = "jdbc:derby:imagesDB;create=true";
private static final String tableName = "imageDB";
private static Connection conn = null;
private static Statement stmt = null;
public void insert(String path, String hash, long FileSize,
String label_name) throws NoSuchAlgorithmException, Exception {
try {
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (\'" + path
+ "\'," + FileSize + ",\'" + hash + "\'" + ",\'"
+ label_name + "\')");
stmt.close();
} catch (SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
public void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
// Get a connection
conn = DriverManager.getConnection(dbURL);
} catch (Exception except) {
except.printStackTrace();
}
}
public void createTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("CREATE TABLE "
+ tableName
+ " (fullPath VARCHAR(512), fileSize INTEGER, md5 VARCHAR(512), label_name VARCHAR(100))");
}
public void indexTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("CREATE INDEX imageDBIndex ON imageDB (fullPath, label_name)");
}
public void deleteTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("drop table " + tableName);
}
public String searchBySizeAndMD(String file_path, long size, String hash)
throws SQLException {
StringBuilder sb = new StringBuilder();
Statement st = conn.createStatement();
ResultSet rs = st
.executeQuery("SELECT fullPath, label_name FROM (SELECT * FROM imageDB im WHERE im.fileSize = "
+ size + " ) as A WHERE A.md5 = " + "\'" + hash + "\'");
while (rs.next()) {
sb.append("Image: (" + rs.getString("fullPath")
+ ") is at label: (" + rs.getString("label_name") + ")\n");
}
return sb.toString();
}
public String searchByImageName(String fileName) throws SQLException {
StringBuilder sb = new StringBuilder();
Statement st = conn.createStatement();
ResultSet rs = st
.executeQuery("SELECT fullPath, label_name FROM imageDB im WHERE im.fullPath like \'%"
+ fileName + "%\'");
while (rs.next()) {
File out_path = new File(rs.getString("fullPath"));
if (!fileName.equals(out_path.getName())) continue;
sb.append("Image: (" + out_path.getPath()
+ ") is at label: (" + rs.getString("label_name") + ")\n");
}
return sb.toString();
}
public void deleteLabel(String label) throws SQLException {
Statement st = conn.createStatement();
st.execute("DELETE FROM " + tableName + " WHERE label_name = \'" + label + "\'");
}
}
Any help in this issue?
The database should be in the folder where you runs the jar. If it's not then check docs how to specify connectionURL. If the project exported to the runnable jar file specify dependent libraries not to be extracted just added as is to the jar or to the local lib folder. These libraries are derby.jar and derbytools.jar should be in the classpath or manifest classpath. Use the following code to test your
Communicate class.
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Communicate {
private static final String dbURL = "jdbc:derby:imagesDB;create=true";
private static final String tableName = "imageDB";
private static Connection conn = null;
private static Statement stmt = null;
public void insert(String path, String hash, long FileSize,
String label_name) throws NoSuchAlgorithmException, Exception {
try {
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (\'" + path
+ "\'," + FileSize + ",\'" + hash + "\'" + ",\'"
+ label_name + "\')");
stmt.close();
System.out.println("Inserted into table "+ tableName+ " values (\'" + path
+ "\'," + FileSize + ",\'" + hash + "\'" + ",\'"
+ label_name + "\')");
} catch (SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
public void loadDriver() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
System.out.println("Loaded the appropriate driver");
} catch (Exception except) {
except.printStackTrace();
}
}
public void createConnection() {
try {
// Get a connection
conn = DriverManager.getConnection(dbURL);
System.out.println("Connected to and created database ");
} catch (Exception except) {
except.printStackTrace();
}
}
public void createTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("CREATE TABLE "
+ tableName
+ " (fullPath VARCHAR(512), fileSize INTEGER, md5 VARCHAR(512), label_name VARCHAR(100))");
System.out.println("Created table "+ tableName);
}
public void indexTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("CREATE INDEX imageDBIndex ON imageDB (fullPath, label_name)");
System.out.println("Created index "+ "imageDBIndex");
}
public void deleteTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("drop table " + tableName);
System.out.println("Deleted table "+ tableName);
}
public String searchBySizeAndMD(String file_path, long size, String hash)
throws SQLException {
StringBuilder sb = new StringBuilder();
Statement st = conn.createStatement();
ResultSet rs = st
.executeQuery("SELECT fullPath, label_name FROM (SELECT * FROM imageDB im WHERE im.fileSize = "
+ size + " ) as A WHERE A.md5 = " + "\'" + hash + "\'");
while (rs.next()) {
sb.append("Image: (" + rs.getString("fullPath")
+ ") is at label: (" + rs.getString("label_name") + ")\n");
}
return sb.toString();
}
public String searchByImageName(String fileName) throws SQLException {
StringBuilder sb = new StringBuilder();
Statement st = conn.createStatement();
ResultSet rs = st
.executeQuery("SELECT fullPath, label_name FROM imageDB im WHERE im.fullPath like \'%"
+ fileName + "%\'");
while (rs.next()) {
File out_path = new File(rs.getString("fullPath"));
if (!fileName.equals(out_path.getName())) continue;
sb.append("Image: (" + out_path.getPath()
+ ") is at label: (" + rs.getString("label_name") + ")\n");
}
return sb.toString();
}
public void deleteLabel(String label) throws SQLException {
Statement st = conn.createStatement();
st.execute("DELETE FROM " + tableName + " WHERE label_name = \'" + label + "\'");
}
public static void main(String[] args)
{
Communicate c = new Communicate();
c.loadDriver();
try {
c.createConnection();
c.createTable();
c.indexTable();
c.insert("/some/path", "12323423", 45656567, "label name");
String s = c.searchBySizeAndMD("/some/path", 45656567, "12323423");
System.out.println("Search result: "+ s);
c.deleteTable();
conn.commit();
System.out.println("Committed the transaction");
//Shutdown embedded database
try
{
// the shutdown=true attribute shuts down Derby
DriverManager.getConnection("jdbc:derby:;shutdown=true");
}
catch (SQLException se)
{
if (( (se.getErrorCode() == 50000)
&& ("XJ015".equals(se.getSQLState()) ))) {
// we got the expected exception
System.out.println("Derby shut down normally");
} else {
System.err.println("Derby did not shut down normally");
System.err.println(" Message: " + se.getMessage());
}
}
} catch (Exception e) {
System.err.println(" Message: " + e.getMessage());
} finally {
// release all open resources to avoid unnecessary memory usage
//Connection
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
System.err.println(" Message: " + e.getMessage());
}
}
System.out.println("Communicate finished");
}
}
This is the output:
Loaded the appropriate driver
Connected to and created database
Created table imageDB
Created index imageDBIndex
Inserted into table imageDB values ('/some/path',45656567,'12323423','label name')
Search result: Image: (/some/path) is at label: (label name)
Deleted table imageDB
Committed the transaction
Derby shut down normally
Communicate finished
I'm using for the first time the connection pool in java. The application that I'm writing is a web application deployed on oracle glassfish 3.1 and the resource connection pool is handled by it. I set the autocommit to false on my connection object, returned by the javax.sql.DataSource, but in the code the rollback command has no effect at all. All the previous operation of write are committed automatically. Is there any other settings in java code that I have to do to disable autocommit? Or there is some configuration settings that I have to do on glassfish?
The database that I'm using is Oracle 10g.
I post here a part of the code that is giving me problem:
private int importFile(String id, String fileName, String label,
String prosumerId, String districtCodes)
throws IOException,
SQLException {
logger.debug("Importing file [" + fileName + "]");
File f = new File(fileName);
BufferedReader br = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String query = "insert into TB_SDK_USER_FILES values ("
+ id + ", '" + label + "', '"
+ fileName.substring(fileName.lastIndexOf("/") + 1) + "', 'active', "
+ "to_date('" + sdf.format(new Date(cal.getTimeInMillis())) + "', 'dd/mm/yyyy hh24:mi:ss'), "
+ "to_date('" + sdf.format(new Date(cal.getTimeInMillis())) + "', 'dd/mm/yyyy hh24:mi:ss'), "
+ "'" + prosumerId + "'"
+ ") ";
logger.debug("Executing query [" + query + "]");
dbl.openDBConnection();
int x = dbl.set(query);
if (x <= 0) {
dbl.rollback();
dbl.closeDBConnection();
logger.error("Insert in TB_SDK_USER_FILES failed, stopping execution ");
return -3;
}
PreparedStatement ps = null;
String line = new String();
try {
br = new BufferedReader(new FileReader(f));
query = "insert into TB_SDK_CONTENTS "
+ "(id, contentCode, cli, content, contentType, PROSUMERID, cld, email) "
+ "values (?,?,?,?,?,?,?,?)";
logger.debug("Executing query [" + query + "]");
ps = dbl.getPreparedStatement(query);
while ((line = br.readLine()) != null) {
String[] tmp = line.split("\t");
if (tmp.length < 4) {
logger.debug("Sono presenti erroneamente meno di 4 valori!!!!");
br.close();
f.delete();
dbl.rollback();
ps.close();
dbl.closeDBConnection();
return -2;
}
ps.setInt(1, new Integer(id).intValue());
String test = tmp[0].replace("*", "");
logger.debug("first column: test [" + test + "]");
try {
if (test.length() > 0) {
double testDouble = Double.parseDouble(test);
//int testInt = Integer.parseInt(test);
}
} catch (NumberFormatException nfe) {
logger.error("The first column does not satisfy the format requested. Found [" + tmp[0] + "] -- NumberFormatException");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -6;
}
if (tmp[0].length() > 0) {
ps.setString(2, tmp[0].trim());
} else {
logger.error("The first column does not satisfy the format requested. Found [" + tmp[0] + "] -- length() <= 0");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -6;
}
test = tmp[1].replace("*", "").trim();
logger.debug("second column: test [" + test + "]");
try {
if (test.length() > 0) {
double testDouble = Double.parseDouble(test);
//int testInt = Integer.parseInt(test);
}
} catch (NumberFormatException nfe) {
logger.error("The second column does not satisfy the format requested. Found [" + tmp[1] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -7;
}
if (tmp[1].length() > 0) {
ps.setString(3, tmp[1].trim());
} else {
logger.error("The second column does not satisfy the format requested. Found [" + tmp[1] + "] -- length() <= 0");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -7;
}
logger.debug("third column: tmp[2] [" + tmp[2] + "]");
ps.setString(4, tmp[2]);
if ((tmp[3].length() > 0) && ((tmp[3].compareToIgnoreCase("TTS") == 0)
|| (tmp[3].compareToIgnoreCase("Audio") == 0))) {
ps.setString(5, tmp[3].trim());
logger.debug("fourth column: tmp[3] [" + tmp[3] + "]");
} else {
logger.error("The fourth column does not satisfy the format requested. Found [" + tmp[3] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -10;
}
ps.setString(6, prosumerId);
if (tmp.length > 4) {
tmp[4] = tmp[4].trim();
if ((tmp[4].length() > 0) && (tmp[4].length() <= 12) && (tmp[4].matches("^\\d*$"))) {
boolean ok = false;
logger.debug("Checking district codes...");
String[] codes = districtCodes.split(",");
for (int i = 0; i < codes.length; i++) {
if (tmp[4].startsWith(codes[i].trim())) {
ok = true;
logger.debug("District code found.");
break;
}
}
if (ok) {
ps.setString(7, tmp[4]);
logger.debug("fifth column: tmp[4] [" + tmp[4] + "]");
} else {
logger.error("The fifth column does not satisfy the format requested. Found [" + tmp[4] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -8;
}
} else if (tmp[4].length() == 0) {
ps.setString(7, "-");
logger.debug("fifth column: tmp[4] [-]");
} else {
logger.error("The fifth column does not satisfy the format requested. Found [" + tmp[4] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -8;
}
} else {
ps.setString(7, "-");
}
if (tmp.length == 6) {
tmp[5] = tmp[5].trim();
if ((tmp[5].length() > 0) && (isValidEmailAddress(tmp[5]))) {
ps.setString(8, tmp[5]);
} else if (tmp[5].length() == 0) {
ps.setString(8, "-");
} else {
logger.error("The sixth column does not satisfy the format requested. Found [" + tmp[5] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -9;
}
} else {
ps.setString(8, "-");
}
x = ps.executeUpdate();
if (x <= 0) {
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
//f.delete();
logger.error("Insert in TB_SDK_CONTENTS failed, stopping execution ");
return -3;
}
}
br.close();
//f.delete();
ps.close();
dbl.commit();
dbl.closeDBConnection();
return 0;
} catch (Exception ex) {
logger.error("An exception occured during the import of file [" + fileName + "] for line [" + line + "]", ex);
dbl.rollback();
if (br != null) {
br.close();
}
if (ps != null) {
ps.close();
}
dbl.closeDBConnection();
//f.delete();
return -1;
}
}
On the other class that handle the DB operation:
public int set(String query) {
Statement statement = null;
int ris = -1;
try {
if (connection == null || !connection.isValid(1)) connect();
logger.debug("Opening statement");
statement = connection.createStatement();
ris = statement.executeUpdate(query);
} catch (SQLException ex) {
logger.error("ERROR in execution of [" + query + "] due to: ", ex);
ris = -1;
} finally {
try {
logger.debug("Closing statement");
if (statement != null) {
statement.close();
}
} catch (SQLException ex1) {
logger.error("ERROR cannot close statement.", ex1);
}
}
return ris;
}
The connection open:
public boolean connect() {
if (dataSource != null) {
try {
connection = dataSource.getConnection();
logger.info("Connection open to DB");
return true;
} catch (SQLException ex) {
logger.error("An error occured during request of connection to datasource, due to...", ex);
return false;
}
}
String url;
if (connectionString.length() > 0) {
url = connectionString;
} else {
url = "jdbc:oracle:thin:#" + host + ":" + port + ":" + sid;
}
try {
// create an OracleDataSource
OracleDataSource ods = new OracleDataSource();
// set connection properties
Properties prop = new Properties();
prop.put("user", user);
prop.put("password", pwd);
ods.setConnectionProperties(prop);
ods.setURL(url);
// get the connection
connection = ods.getConnection();
connection.setAutoCommit(false);
((OracleConnection) connection).setDefaultRowPrefetch(10);
logger.info("Connection open to DB");
return true;
} catch (Exception ex) {
logger.info("An exception occured in execution of [connect]. ");
if (dataSource == null) {
logger.error("[" + url + ", " + user + ", " + pwd + "] ERROR in execution of [connect] due to: ", ex);
}
return false;
}
}
dataSource getConnection():
public static Connection getConnection() throws SQLException {
Connection con = dataSource.getConnection();
con.setAutoCommit(false);
return con;
}
The lookup for the data source is done in the Context Listener at context creation.
Edit:
I'm reading again the oracle tutorials about the usage of pooling connection and other links about it: every example the open and close of the connection to the pool is done in the same method. I thought that was just a need to be more simplest to explain all the steps, but I'm wondering if this is not also a need to satisfy the "transaction" at connection pool level. Can anyone confirm me this? Or give me a documentation link where this is well explained? Thank you very much!