i’m gonna create class that will operate on database. The class will have functions addRecord(), getAllRecords(), stuff like that. I’m looking for a good approach to design the class. Should i have to:
1) create new Connection for every function. Like this:
void readRecords(){
try {
Connection con = DriverManager.getConnection (connectionURL);
Statement stmt = con.createStatement();
ResultSet rs = stmd.executeQuery("select moviename, releasedate from movies");
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate");
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
con.close();
}
}
or
2) it’s better to have one connection as a memeber variable
class MyClass{
private Connection con;
public MyClass(){
con = DriverManager.getConnection (connectionURL);
}
}
and create just the statement for every function.
3) or something else…
If there are frequent regular jdbc calls, then use a database connection pool.