Okay so there are many problems with your code. First off,
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
You would have to pass a Driver implementation, not the interface itself; but the good news is that this code is unnecessary as of JDBC 4.0. It already scans your classpath to locate drivers for you.
Second, your connection is not being closed with each query. There's nowhere in your code where you're calling connec.close()
. JDBC won't close the connection for you, either.
Third, you don't need to do this with nested for loops! That is an awful idea. Your concept of SQL queries and JDBC needs some sharpening. You can simply do the following:
for(int i=0;i<identities.length;i++) {
String sql = "SELECT * FROM cgm_counters WHERE id="+identities[i];
ResultSet 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);
}
}
Even better would be to do a batch query.
String batch = "(";
for (int i = 0; i < identities.length;i++) {
if (i < identities.length() - 1)
batch += "?, ";
else
batch += "?)"
}
String sql = "SELECT * FROM cgm_counters WHERE id in " + batch;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
double net_ppe = rs.getDouble("spend");
System.out.println("The value of the netppe :"+net_ppe);
}
It seems you are doing a preliminary round of queries to "check" whether each ID is in the table, but this is not necessary. If the ID is not in the table, then you'll get an empty result set in return. There's nothing wrong with an empty result set. Your while loop will never run in this case because rs.next()
will return false. You can also check whether it's empty by calling rs.first()
. This way doesn't move the cursor.