Java - insert does not occurred only first time

Asked By anbu n on 13-Jan-12 06:01 AM
Earn up to 10 extra points for answering this tough question.
java.sql.CallableStatement cs; 
Connection con = null;

 try {
  Class.forName("com.mysql.jdbc.Driver");
  String url = "jdbc:mysql://system10/gateway_v1";

  con = DriverManager.getConnection(url, "binarch","binarch");
  cs = con.prepareCall("{ call Test_Insert(?) }");
  cs.setString(1,"TVS");
  
  // Execute the stored procedure
  cs.execute();  

  
 } catch (Exception e) {
  e.printStackTrace();
  System.out.println("Exception: " + e.getMessage());
 } finally {
  try {
   if (con != null)
    con.close();
  } catch (SQLException e) {    
  }
 }

------------------------
in above code only insert happened only one time, after that insert does not happen & also no error is generated.

can somebody give suggestion , since tis is first time i am coding in java.

thanks


D Company replied to anbu n on 15-Jan-12 05:40 AM
hello friend,

what  here i can understand by your code that,

1. it seems there is a problem with either you DB connection or the logic you have used to interact with DB.
2. second time when you try to insert the data , I'm not sure whether the connection is again opening properly.

Suggestions

1. what i can suggest here is to trace your code in each cases(first time as well as second time) when you trying to insert the data
2. most importantly try to close the connection in try block itself once the SP gets execute.



Let us know if u need more assistance on this

Regards
D
[)ia6l0 iii replied to anbu n on 30-Jan-12 01:12 PM
It does not matter if you are coding for the first time or not. 

The code snippet that you posted seems to be calling a 'Test_Insert'  stored procedure to insert some sample data. This insert seems to be called only once, and that is why it works the first time. 

If that does not work for the second time, then you have some code bugs. I would rewrite your code as below.  I have added inline comments to explain the changes.

java.sql.CallableStatement cs; 
Connection con = null;

try 
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://system10/gateway_v1";
con = DriverManager.getConnection(url, "binarch","binarch");
cs = con.prepareCall("{ call Test_Insert(?) }");
cs.setString(1,"TVS");
// Execute the stored procedure
cs.execute();  

//Place generic exceptions at the end. So call SQL Exception before General Exception.
catch (SQLException e) 
{    
e.printStackTrace();
System.out.println("SQL Exception: " + e.getMessage());
}
catch (Exception e) 
{
e.printStackTrace();
System.out.println("Exception: " + e.getMessage());
}
finally 
{
//Your finally block needs to be clean. The following statements are enough.
if (con != null)
con.close();
}

Hope this helps.