Reputation: 149
I have started to learn the JDBC as i want a plugin i am creating to connect with a database, i have it working right now but one thing i don't like is i have an insert query within a for loop which of course is bad. How would i achieve the same thing but with only one query? and also is the rest of my queries okay as in practise wise
open(); // opens a connection from a method
try{
PreparedStatement sql = con.prepareStatement("INSERT INTO `score` (player, score) VALUES (?,?);");
sql.setString(1, "test");
sql.setInt(2, 1);
sql.execute();
sql.close();
}catch(Exception e){
e.printStackTrace();
}
try{
PreparedStatement s = con.prepareStatement("SELECT COUNT(*) AS rowcount FROM score"); // get the number of rows
ResultSet r = s.executeQuery();
r.next();
int count = r.getInt("rowcount") / 2; // divide total rows by 2
int q = Math.round(count);
r.close();
s.close();
PreparedStatement ss = con.prepareStatement("SELECT id FROM score ORDER BY score DESC LIMIT ?;"); // get the top half of results with the highest scores
ss.setInt(1, q);
ResultSet rs = ss.executeQuery();
while(rs.next()){
PreparedStatement qq = con.prepareStatement("INSERT INTO `round2` (player, score) VALUES (?,?);"); //this is the insert query
qq.setString(1, rs.getString("player"));
qq.setInt(2, 0);
qq.execute();
qq.close();
}
rs.close();
ss.close();
}catch(Exception e){
e.printStackTrace();
}
close(); //close connection
Upvotes: 0
Views: 665
Reputation: 20182
You can use updateBatch on the Statement/PreparedStatement- this way, you can batch the inserts into the database instead of sending in so many inserts into the database as separate jobs.
For instance:
import java.sql.Connection;
import java.sql.PreparedStatement;
//...
String sql = "insert into score (player, score) values (?, ?)";
Connection connection = new getConnection(); //use a connection pool
PreparedStatement ps = connection.prepareStatement(sql); //prefer this over statement
for (Player player: players) { //in case you need to iterate through a list
ps.setString(1, player.getName()); //implement this as needed
ps.setString(2, player.getScore()); //implement this as needed
ps.addBatch(); //add statement to batch
}
ps.executeBatch(); //execute batch
ps.close(); //close statement
connection.close(); //close connection (use a connection pool)
Hope it helps
Upvotes: 3