java - Is it better to have one always open connection or is it better to establish a connection each time something is needed? -


currently program establishes connection server each time needs , closes connection after grabs needs.

connection con = drivermanager.getconnection(url, user, pass);       //grab data       con.close(); 

is better or worse practice , difference make if had 1 global connection running start of program.

public static connection con = drivermanager.getconnection(url, user, pass); 

and referenced wherever needed like

classname.con.createstatement(); 

this depends on application. should code need -- 1 session big application can introduce problems.

for example thread safety. if multiple users connected application 1 session / connection out of scope.

i use 1 connection per request -- additional connection pool , maximum amount of open connections.

and because using connection can throw exceptions put code inside try-with-resources block , connection closed automatically.

try (connection con = drivermanager.getconnection(myconnectionurl);) {     // grab data } catch (sqlexception e) {     e.printstacktrace(); } 

Comments