Reputation: 69
I am implementing a code that uses JDBC driver.
Below is the code that I made.
public class MysqlUtils {
public Connection conn;
public ResultSet rs;
public PreparedStatement stmt;
public MysqlUtils(String address, String id, String passwd) {
try {
conn = DriverManager.getConnection(address, id, passwd);
stmt = null;
rs = null;
} catch (SQLException e) {
// error management
}
}
public void getSomeData(long id) {
try {
stmt = conn.prepareStatement("SELECT * FROM some_table");
rs = stmt.executeQuery();
rs.next();
System.out.println(rs.getString("some_column");
} catch (SQLException e) {
// error management
}
}
}
I have declared Connection conn, ResultSet rs, PreparedStatement stmt as member variables because somehow I thought that might help me enhance performance.
I have a couple of questions.
If I call getSomeData() consecutively, will stmt and rs be assigned new objects every time?
Regardless of the answer to the question above, if I run this code in a multi-threaded environment(multiple threads using MysqlUtils class), will there be a mix-up because I didn't declare ResultSet rs in getSomeData()?
Was declaring Connection conn, ResultSet rs, PreparedStatement stmt as member variables a bad choice? In other words, is my implementation of JDBC a viable one?
Thanks for the help.
Upvotes: 0
Views: 1242
Reputation: 692073
stmt
and rs
will take new values. Of course, you might have multiple instances of your class, and thus multiple instances of those two fields.Also:
getSomeData()
should return something, and not just printing somethingI would advise using spring-jdbc, which takes care of all the plumbing code for you, and avoids all the problems your code currently has.
Upvotes: 1
Reputation: 55
Do not use ResultSet outside of the method.... with while(rs.next) (rs=resultSet) you are looping through a database table and retrieving values!
Upvotes: 0