I have a batch process program in place where I am using JDBC to make calls to the database. I am sending information in a batch of 100 with 'ID' as the primary key.
I want to make a single call to the database and then execute multiple SQL statements before closing the connection.
I am posting portion of the code for reference
// Database credentials
String USER = username;
String PASS = password;
Connection connec = null;
Statement stmt = null;
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
connec = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = connec.createStatement();
// Step 2: To update the database with the new count and the netppe values.
// Step to know whether the ID is present or not in the database
for(int i=0;i<identities.length;i++){
String booleanString = "SELECT 1 FROM cgm_counters WHERE id = "+identities[i];
stmt.execute(booleanString);
ResultSet resultSet = stmt.getResultSet(); //result set for records
boolean recordFound = resultSet.next();
ResultSet rs = null;
// Retrieve the 'netppe' information.
if(recordFound){
String sql = "SELECT * FROM cgm_counters WHERE id="+identities[i];
rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
double net_ppe = rs.getDouble("spend");
System.out.println("The value of the netppe :"+net_ppe);
}
}// end of 'If' statement
I want to do three things in one go for each ID in the for loop.
1 > I want to see whether the ID is present or not in the database
2 > If ID - present
{
2 a > retrieve the 'netppe' information for that particular ID
2 b > retrieve the 'count' information for that same ID
2 c> Update the database with the new 'netppe' and 'count' value for the same ID
} else {
Insert the information for the new ID
}
How to execute all the statements without having to close the connection for each ID? New to JDBC and SQL. Any help is appreciated.