java - Best way to access a database -
i'm relatively new java. i'm tinkering small program uses jframe few fields query , insert database.
i have class nothing creates database connection. there, have other classes perform select or insert database functions. each of these starts creating new object database connection class. connection closed when finished.
being new this, wanted see if best way access database, ie: creating , closing brand new connection each time button pressed. performs task needed, if there's more efficient or sensible way i'd love know.
i can provide whatever code may need see. thanks!
usual way access database java connection pool. recommend one: http://jolbox.com/
in database interaction code creates connection pool (actually borrows connection pool) , after requests close connection (actually returns connection pool).
public class dao { private final datasource ds; public void foo(...) { connection connection = ds.getconnection(); try { // work there } { connection.close(); } } } public class mainpanel extends jpanel { private final dao dao; public mainpanel(dao dao) { this.dao = dao; } // ... } public class main { public static void main(string[] args) { class.forname("org.hsqldb.jdbcdriver"); bonecpdatasource ds = new bonecpdatasource(); ds.setjdbcurl("jdbc:hsqldb:mem:test"); ds.setusername("sa"); ds.setpassword(""); dao dao = new dao(ds); mainpanel mainpanel = new mainpanel(dao); // ... } }
Comments
Post a Comment