ObjectInputStream works for MySql, but not for sqlite - java

I use this code to get a Blob from a MySql database and it works fine, when i use it for an sqlite database it throws a StreamCorruptedException
public static SessionData getIvissSession(BigInteger id) throws IvissDatabaseException {
SessionData sd = null;
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con.prepareStatement("SELECT ivissblob FROM iviss_session_table WHERE id =?");
pstmt.setLong(1, Long.parseLong(id.toString()));
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
byte[] ivissblob = rs.getBytes("ivissblob");
ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(ivissblob));
sd = (SessionData) objectIn.readObject();
objectIn.close();
}
} catch (SQLException e) {
throw new IvissDatabaseException(Constants.ERROR_202);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return sd;
When I use the SqLite Database:
java.io.StreamCorruptedException: invalid stream header: 61742E75
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:797)
at java.io.ObjectInputStream.(ObjectInputStream.java:294)
Why is there a differnt behaviour?
Here how I write into the database:
public static void insertIntoTable(BigInteger id, SessionData sd, byte[] rtsd, IvissWorker ivissWorker) {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con
.prepareStatement("REPLACE INTO iviss_session_table (id, ivissblob, rtblob, lastaccess) VALUES(?,?,?,?)");
pstmt.setLong(1, Long.parseLong(id.toString()));
pstmt.setObject(2, sd);
pstmt.setObject(3, rtsd);
pstmt.setDate(4, new Date(System.currentTimeMillis()));
pstmt.executeUpdate();
} catch (SQLException e) {
ivissWorker.getIvissWorkerOutputHandler().addError(Constants.ERROR_205, "", DbConfiguration.getDbUri());
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Additional information sqlite driver version:
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>

a solution of the problem given from a colleague:
Insert the object not with method .setObject, but with .setBytes instead.
public static void insertIntoTable(BigInteger id, SessionData sd, byte[] rtsd, IvissWorker ivissWorker) {
PreparedStatement pstmt = null;
Connection con = null;
try {
con = getConnection();
pstmt = con
.prepareStatement("REPLACE INTO iviss_session_table (id, ivissblob, rtblob, lastaccess) VALUES(?,?,?,?)");
pstmt.setLong(1, Long.parseLong(id.toString()));
pstmt.setBytes(2, IvissUtil.getBytes(sd));
pstmt.setObject(3, rtsd);
pstmt.setDate(4, new Date(System.currentTimeMillis()));
pstmt.executeUpdate();
// System.out.println("Stored/Replaced session with ID: " + id +
// " in table.");
} catch (SQLException e) {
ivissWorker.getIvissWorkerOutputHandler().addError(Constants.ERROR_205, "", DbConfiguration.getDbUri());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
and the getBytes method:
public static byte[] getBytes(Object obj) throws java.io.IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte[] data = bos.toByteArray();
return data;
}
Now it works with sqlite and MySql

Related

insert single data in data base but in data base duplicate row also added at time of insertion

I would like to insert single data in data base at a time but in data base duplicate row generate at a time.
-----------------------------
Output(in mysql table=privilege)
-----------------------------
id privilege
1 abc
2 abc
Here's how I insert the data:
public int addPrivilege(String privilege) {
PreparedStatement preparedStatement = null;
String sqlprivilege;
Connection dbConnection = null;
int pinsert = 0;
try {
sqlprivilege = "insert into privilege(privilege) values(?)";
dbConnection = ConnectionDao.getDBConnection();
preparedStatement = dbConnection.prepareStatement(sqlprivilege);
preparedStatement.setString(1, privilege);
pinsert = preparedStatement.executeUpdate();
if(preparedStatement.executeUpdate()==1)
pinsert=1;
else
pinsert=0;
System.out.println("privilege is add and name is:- " +privilege);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return pinsert;
}
You execute the sql twice in your code.
1) pinsert = preparedStatement.executeUpdate();
2) if(preparedStatement.executeUpdate()==1)
I'm not sure about the return values of the executeUpdate. But i think the first is enough, no need to check for the return values. If you need to then compare with pinsert instead of executeupdate (again).
if(pinsert == 1)
You are using two time executeUpdate(); delete execute which one is in if case
public int addPrivilege(String privilege) {
PreparedStatement preparedStatement = null;
String sqlprivilege;
Connection dbConnection = null;
int pinsert = 0;
try {
sqlprivilege = "insert into privilege(privilege) values(?)";
dbConnection = ConnectionDao.getDBConnection();
preparedStatement = dbConnection.prepareStatement(sqlprivilege);
preparedStatement.setString(1, privilege);
pinsert = preparedStatement.executeUpdate();
//try this
if(pinsert ==1)
pinsert=1;
else
pinsert=0;
System.out.println("privilege is add and name is:- " +privilege);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return pinsert;
}

"Operation not allowed after ResultSet closed" with Datasource and crawler4j

After reading through a lot of similar questions I have not been able to get a solution that works for me.
I have this methods:
In a crawler4j Controller I do this:
ArrayList<String> urls = Urls.getURLs(100);
for (String s : urls) {
System.out.println("Adding URL: " + s);
controller.addSeed(s);
}
this is getURLs():
public static ArrayList<String> getURLs(int number) {
ArrayList<String> list = new ArrayList<String>();
String getStatement = "select * from " + Configurations.getStringProperty("mysql.urls.db_name", "urls") + " where retrieved=0 limit "
+ Configurations.getStringProperty("mysql.urls.limit", "100") + ";";
ResultSet rs;
rs = Databaseclient.executeStatement(getStatement);
try {
while (rs.next()) {
list.add(rs.getString("url"));
// Databaseclient.executeStatement("update urls set retrieved = true where id = "
// + rs.getInt("id") + ";");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
This is my executeStatement():
public static ResultSet executeStatement(String s) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// fetch a connection
connection = DataSource.getInstance().getConnection();
if (connection != null) {
statement = connection.createStatement();
resultSet = statement.executeQuery(s);
}
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
} catch (IOException e) {
System.out.println("A IOException occured executing the Statement");
e.printStackTrace();
} catch (PropertyVetoException e) {
System.out.println("A PropertyVetoException occured executing the Statement");
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
}
}
}
return resultSet;
}
I get the error
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1094)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:997)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:983)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:928)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:799)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6982)
at database.Urls.getURLs(Urls.java:27)
at crawler.Controller.main(Controller.java:53)
Which is the line
while (rs.next()) {
in my getURLs() method.
What am I doing wrong? There is no code between getting the statement and the while loop that could close the statement.
Your code is a bit off, but if I understand you then don't close your ResultSet in the finally block of your executeStatement method.
public static ResultSet executeStatement(Connection connection,
Statement statement, String s) {
ResultSet resultSet = null;
try {
if (statement != null) {
resultSet = statement.executeQuery(s);
}
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
} catch (IOException e) {
System.out.println("A IOException occured executing the Statement");
e.printStackTrace();
} catch (PropertyVetoException e) {
System.out.println("A PropertyVetoException occured executing the Statement");
e.printStackTrace();
}
return resultSet;
}
Then you need to pass in a Connection and Statement, and you'll get a ResultSet back. Also, the caller should then close all three when it's done with the ResultSet.

using combobox selectedItem on a function

i have an function connexion to a database
and i have a code that i have a select and display elements in a combobox
so i want pass on class connexion.java the combobox selectedItem becaue it contains the all of databases that i have
so i want tha classe connexion be dynamic so pass the element selected on this class
i don"t know how can i do that please help me
public class Connexion {
private static Connection conn;
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456");
} catch (SQLException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }
}
public static Connection getconx()
{
return conn;
}
}
Use this class
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;
import org.apache.commons.dbcp.BasicDataSource;
import sun.jdbc.rowset.CachedRowSet;
public class SQLConnection {
private static Connection con = null;
private static BasicDataSource dataSource;
//we can enable and disable connection pool here
//true means connection pool enabled,false means disabled
private static boolean useConnectionPool = true;
private static int count=0;
private SQLConnection() {
/*
Properties properties = new Properties();
properties.load(new FileInputStream(""));
maxActive = properties.get("maxActive");
*/
}
public static String url = "jdbc:mysql://localhost:3306/schemaname";
public static String password = "moibesoft";
public static String userName = "root";
public static String driverClass = "com.mysql.jdbc.Driver";
public static int maxActive = 20;
public static int maxIdle = 10;
private static final String DB_URL = "driver.classs.name";
private static final String DB_USERNAME = "database.username";
static {
/*Properties properties = new Properties();
try {
properties.load(new FileInputStream("D:\\CollegeBell\\properties\\DatabaseConnection.properties"));
//properties.load(new FileInputStream("E:\\vali\\CollegeBell\\WebContent\\WEB-INF"));
//properties.load(new FileInputStream("D:\\DatabaseConnection.properties"));
url = properties.getProperty(DB_URL);
System.out.println(url);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(maxIdle);
dataSource.setMaxIdle(maxIdle);
}
//public static Connection getConnection(String opendFrom) throws SQLException,
public static Connection getConnection(String openedFrom) {
count++;
System.out.println("nos of connection opened till now="+count);
System.out.println("Connection opended from "+openedFrom);
// System.out.println("Connection Opended ");
try {
if (useConnectionPool) {
con = dataSource.getConnection();
System.out.println(dataSource.getMinEvictableIdleTimeMillis());
//dataSource.setMaxWait(15000);
System.out.println(dataSource.getMaxWait());
System.out.println(count );
} else {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, userName, password);
}
}
//System.out.println("Connection : " + con.toString());
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void closeConnection(Connection con, String closedFrom)
{
//System.out.println("Connection closed from: " + con.toString());
// System.out.println("Connection closed from: " + closedFrom);
//log.info("Connection closed from: " + closedFrom);
if(con != null){
count--;
System.out.println("Connection count value after closing="+count);
System.out.println("Connection closed from: " + closedFrom);
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//added by nehal
public static void closeStatement(Statement ps, String closedFrom)
{
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closePreparedStatement(PreparedStatement ps, String closedFrom)
{
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closeResultSet(ResultSet rs, String closedFrom)
{
if(rs != null){
System.out.println("ResultSet closed from: " + closedFrom);
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//added by nehal
/*public static ResultSet executeQuery(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
CachedRowSet crset = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
crset = new CachedRowSet();
crset.populate(rs);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return crset;
}
public static int executeUpdate(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
int rows = -1;
try {
con = getConnection();
stmt = con.createStatement();
rows = stmt.executeUpdate(query);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return rows;
}
public static boolean execute(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
boolean rowsreturned = false;
try {
con = getConnection();
stmt = con.createStatement();
rowsreturned = stmt.execute(query);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return rowsreturned;
}*/
/*
* public static void closeConnection(Connection con) { try { con.close();
* con=null; } catch (SQLException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } }
*/
}
A JComboBox accepts any kind of object, so you can simply do something like this.
Connection con = new Connection();
JComboBox box = getBox();
box.addItem(con);
And to retreive the value:
JComboBox box = getBox();
Connection con = (Connection)box.getSelectedItem();
However in your Connection class you must override the toString() function, because this is used to display the box.
class Connection
{
public String toString()
{
return "BoxItemDisplayvalue"; <--- here you must put something meaningfull which is displayed in the box.
}
}
So you can instantiate a connection representing the connection that you want, and when the user selects an item from the combobox, you will have the connection it represents.
For what i understand, you have 2 classes..
One the gui where you have a comboBox with the schema name where u want to get connected.
So you have to have a EventListener to "listen" when the submit button is pressed.
For example:
Connection con = null;
JButton submitButton = new JButton("Confirm db");
submitButton.addActionListener(new MyConnectionListener());
..
//Could be inner class
class MyConnectionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent evt){
if(cmb.getSelectedItem() != null){
con = Connection.getConx(cmb.getSelectedItem().toString());
}
}
}
And in your Connexion class
public class Connexion {
public static Connection getconx(String schema)
{
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/"+schema, "root", "123456");
} catch (SQLException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }
}
return conn;
}
}

can't get connection to database through java class

i'm trying to establish connection with mysql database through file properties and then run the information from servlet. my Connection class looks like this:
public class pageDao {
private Connection connection;
private Statement statement;
private pageDao() {
Properties prop = new Properties();
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " +cnfe);
}
try {
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String db = prop.getProperty("database");
String dbuser = prop.getProperty("dbuser");
String dbpassword = prop.getProperty("dbpassword");
connection = DriverManager.getConnection(db,dbuser,dbpassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static pageDao thisDao;
public static pageDao gedDao()
{
if(thisDao == null)
thisDao = new pageDao();
return thisDao;
}
public PageData getPage(String id)
{
PageData data = new PageData();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from pages where id='"+id+"'");
if(rs.next())
{
data.setId(rs.getString("id"));
data.setParentid(rs.getString("parentid"));
data.setTitle(rs.getString("title"));
data.setTitle4menu(rs.getString("title4menu"));
data.setKeywords(rs.getString("keywords"));
data.setDescription(rs.getString("description"));
data.setMaintext(rs.getString("maintext"));
}
else
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
when i run it, it doesn't show the mistake that connection wasn't established, but when it gets to the
public PageData getPage(String id) {
PageData data = new PageData();
try {
statement = connection.createStatement();
it throws java.lang.NullPointerException.
can anybody help me out with that?
there is no issue with code.
check your passing parameter ...
check sample
private Connection getConnection() {
try {
String dbUrl = "jdbc:mysql://localhost:3306/projectmining";
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(dbUrl, "root", "admin");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

org.apache.commons.dbcp.DelegatingPreparedStatement is closed

org.apache.commons.dbcp.DelegatingPreparedStatement
is closed
Could i know in which situations this exception will come.
I closed all result sets and prepared statements.
How can i solve this problem.
Code :
public int UpdateMovementLines(List<MaterialRequestIssuanceVO> mlinelist,String projId,String documentno,String user){
int count = 1;
int line = 0;
String uom = null;
String projLocatorId = null;
String projWarehouseId = null;
String warehouseLocatorId = null;
String issuanceId = null;
String movementLineId =null;
String pinstanceId = null;
String sqlQry = null;
String whLocatorId = null;
PreparedStatement ps = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
PreparedStatement ps3 = null;
PreparedStatement ps4 = null;
PreparedStatement ps5 = null;
ResultSet rs = null;
ResultSet rs1 = null;
ResultSet rs2 = null;
ResultSet rs3 = null;
try{
conn.setAutoCommit(false);
try{
sqlQry="INSERT INTO m_movement (m_movement_id, AD_CLIENT_ID, AD_ORG_ID, CREATED, CREATEDBY, UPDATED, UPDATEDBY," +
"name, movementdate, posted, processing, move_fromto_locator,documentno) VALUES " +
"(?,?,?,NOW(),?,NOW(),?,to_char(now(),'DD-MM-YYYY'),now(),?,?,?,?)";
ps = conn.prepareStatement(sqlQry);
for(MaterialRequestIssuanceVO movementvo:mlinelist){
issuanceId = movementvo.getIssuanceid();
ps.setString(1, issuanceId);
ps.setString(2,movementvo.getClientid());
ps.setString(3,movementvo.getOrgid());
ps.setString(4, movementvo.getCreatedby());
ps.setString(5,movementvo.getUpdatedby());
ps.setString(6,"N");
ps.setString(7,"N");
ps.setString(8,"N");
ps.setString(9, documentno);
count=ps.executeUpdate();
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
log4j.info("Inside DB Line saveMRIssuanceMovementData Exception"+e);
}
finally
{
try
{
ps.close();
log4j.info("Inside Line Finally");
} catch (SQLException e) {
e.printStackTrace();
}
}
ps=conn.prepareStatement("select c_uom_id as uom from m_product where m_product_id = ?");
for(MaterialRequestIssuanceVO movementvo:mlinelist){
line = line +10;
ps.setString(1, movementvo.getMaterialid());
rs = ps.executeQuery();
while(rs.next())
{
uom = rs.getString("uom");
log4j.info("Uom: "+uom);
}
try{
ps2=conn.prepareStatement("select m_locator_id as locatorid from m_locator where m_warehouse_id = ?");
ps2.setString(1, movementvo.getWarehouseId());
rs2 = ps2.executeQuery();
while(rs2.next())
{
warehouseLocatorId = rs2.getString("locatorid");
log4j.info("warehouseLocatorId: "+warehouseLocatorId);
}
}catch(SQLException e){
log4j.info("Warehouse Locator Exception: "+e);
}
finally{
rs2.close();
ps2.close();
}
try{
ps3=conn.prepareStatement("select m_locator_id as locatorid from m_locator where m_warehouse_id=? and value like ?");
ps3.setString(1, movementvo.getWarehouseId());
ps3.setString(2, projId);
rs3 = ps3.executeQuery();
if(rs3.next())
{
projLocatorId = rs3.getString("locatorid");
log4j.info("projLocatorId: "+projLocatorId);
}
else
{
sqlQry="INSERT INTO m_locator (m_locator_id, AD_CLIENT_ID, AD_ORG_ID, CREATED, CREATEDBY, UPDATED, UPDATEDBY," +
"value, m_warehouse_id, priorityno, x,y, z) VALUES " +
"(?,?,?,NOW(),?,NOW(),?,?,?,?,?,?,?)";
ps4 = conn.prepareStatement(sqlQry);
try
{
whLocatorId = SequenceIdData.getUUID();
log4j.info("issueid: "+whLocatorId);
ps4.setString(1, whLocatorId);
log4j.info("Client Id: "+movementvo.getClientid());
ps4.setString(2,movementvo.getClientid());
log4j.info("Orgid: "+movementvo.getOrgid());
ps4.setString(3,movementvo.getOrgid());
ps4.setString(4, movementvo.getCreatedby());
ps4.setString(5,movementvo.getUpdatedby());
ps4.setString(6,projId);
ps4.setString(7,movementvo.getWarehouseId());
ps4.setInt(8,50);
ps4.setString(9,"x");
ps4.setString(10,"y");
ps4.setString(11,"z");
count=ps4.executeUpdate();
if(count == 1)
projLocatorId = whLocatorId;
}
catch(SQLException e)
{
log4j.info("M_Locator Exception: "+e);
}
finally
{
ps4.close();
}
log4j.info("whLocatorId projLocatorId: "+projLocatorId);
}
}catch(SQLException e){
log4j.info("Locator Exception: "+e);
}
finally{
rs3.close();
ps3.close();
}
try{
sqlQry="INSERT INTO m_movementline (m_movementline_id, AD_CLIENT_ID, AD_ORG_ID, CREATED, CREATEDBY, UPDATED, UPDATEDBY," +
"m_movement_id, m_locator_id, m_locatorto_id, m_product_id,line, movementqty,c_uom_id,m_attributesetinstance_id) VALUES " +
"(?,?,?,NOW(),?,NOW(),?,?,?,?,?,?,?,?,?)";
ps1 = conn.prepareStatement(sqlQry);
movementLineId = SequenceIdData.getUUID();
ps1.setString(1, movementLineId);
ps1.setString(2,movementvo.getClientid());
ps1.setString(3,movementvo.getOrgid());
ps1.setString(4, movementvo.getCreatedby());
ps1.setString(5,movementvo.getUpdatedby());
ps1.setString(6,issuanceId);
ps1.setString(7,warehouseLocatorId);
ps1.setString(8,projLocatorId);
ps1.setString(9,movementvo.getMaterialid());
ps1.setInt(10,line);
ps1.setInt(11,Integer.parseInt(movementvo.getIssuedqty()));
ps1.setString(12,uom);
ps1.setString(13,"0");
count=ps1.executeUpdate();
}
catch(SQLException e){
log4j.info("Inside DB MoveLines SQLException"+e.getMessage());
}
finally
{
try
{
ps1.close();
log4j.info("Inside movement Line Finally");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
sqlQry="INSERT INTO ad_pinstance (ad_pinstance_id, AD_CLIENT_ID, AD_ORG_ID, CREATED, CREATEDBY, UPDATED, UPDATEDBY," +
"ad_process_id, record_id, isprocessing, ad_user_id,result) VALUES " +
"(?,?,?,NOW(),?,NOW(),?,?,?,?,?,?)";
ps5 = conn.prepareStatement(sqlQry);
for(MaterialRequestIssuanceVO movementvo:mlinelist){
try{
pinstanceId = SequenceIdData.getUUID();
log4j.info("pinstanceId: "+pinstanceId);
ps5.setString(1, pinstanceId);
log4j.info("Client Id: "+movementvo.getClientid());
ps5.setString(2,movementvo.getClientid());
log4j.info("Orgid: "+movementvo.getOrgid());
ps5.setString(3,movementvo.getOrgid());
ps5.setString(4, movementvo.getCreatedby());
ps5.setString(5,movementvo.getUpdatedby());
ps5.setString(6,"122");
ps5.setString(7,issuanceId);
ps5.setString(8,"N");
ps5.setString(9,user);
ps5.setInt(10, Integer.parseInt("1"));
count=ps5.executeUpdate();
}
catch(SQLException e){
log4j.info("saveMRIssuanceMovementData Line SQLException"+e.getMessage());
}
finally
{
try
{
ps5.close();
log4j.info("Inside movement Line Finally");
} catch (SQLException e) {
e.printStackTrace();
}
}
try{
ps=conn.prepareStatement("select m_movement_post(?)");
ps.setString(1, pinstanceId);
rs = ps.executeQuery();
while(rs.next()){
log4j.info("Result Set: "+rs.getString(1));
}
}catch(SQLException e){
log4j.info("Movement Post Exception: "+e);
}
finally{
ps.close();
}
}
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
count = 0;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Above Mensined Exception Catching hear
log4j.info("Inside DB saveMRIssuanceMovementData Line SQLException"+e.getMessage());
}
finally
{
try
{
if(conn != null)
conn.close();
}
catch(SQLException e)
{
}
}
return count;
}
PreparedStatement is closed
You can get this exception when you're trying to (re)use a PreparedStatement while it has been closed. Check the line number of the first line in the stacktrace. It should hint which PreparedStatement it is talking about. Then backtrack its use in the code and fix code accordingly.
Judging the flood of code you've posted, I suspect that it's the ps5 which is been created before a for loop and been closed inside the for loop. Here's an extract of relevance from your code:
ps5 = conn.prepareStatement(sqlQry);
for (MaterialRequestIssuanceVO movementvo : mlinelist) {
try {
ps5.setString(1, string);
ps5.executeUpdate();
} finally {
ps5.close(); // You're closing inside the loop!
}
}
The next iteration in the loop won't be able to reuse the same PreparedStatement anymore. The fix is obvious: close it after completion of the for loop.
try {
ps5 = conn.prepareStatement(sqlQry);
for (MaterialRequestIssuanceVO movementvo : mlinelist) {
ps5.setString(1, string);
ps5.executeUpdate();
}
} finally {
ps5.close();
}
That said, logging all exceptions as Info or doing only e.printStackTrace() and suppressing them and continuing the code flow isn't always a good idea. Log them as Error and then hard-throw thereafter.
} catch (Exception e) {
logger.error("Your message", e);
throw e;
}
Rethrowing isn't needed for exceptions during close, but logging them as Warn is useful.
Last but not least, consider refactoring the exceptionally large method block into separate and sensible methods (tasks) ;)

Categories