mysql - Managing database connections in java -
a full day of googling problem has left me more confused ever i'm appealing help. i'm trying use pooled connections mysql db i'm misunderstanding something. below snippets of code application scans folder new directories represent "jobs"; when found, database objects created each folder found. based _insert() method on pattern found on so. understanding connections closed , returned connection pool. however, noticed that, after adding 8 objects, code hang on getconnection(). found somewhere default number of active connections 8, added debug line limit number of active connections 2. sure enough, 2 objects added before code hangs.
what's going on? need change make these connections freed , added pool? found one post mentioned poolableconnection class i'm confused documentation fact other examples i've found don't seem use it.
the scanner class creates job objects in database based on folders found in particular directory on disk:
public class scanner extends thread { public void run() { syncjobs(); } void syncjobs(list<string> foldernames) { (string foldername : foldernames) { job job = addjobtodb(foldername); } } job addjobtodb(string foldername ) { job job = new job(); job.name = foldername; job.save(); return job; } }
there's abstract base class objects (each objects overrides _insert):
public abstract class dbobject { private final int insert() { return _insert(); } public final void save() { if (id == 0) id = insert(); else update(); } }
and there's actual job object (with insert method shown):
public class job extends dbobject { public int _insert() { string query = "insert jobs (name) values (?)"; connection conn = null; preparedstatement ps = null; resultset rs = null; int id = 0; try { conn = database.getconnection(); ps = conn.preparestatement(query, statement.return_generated_keys); ps.setint(1, id); ps.executeupdate(); rs = ps.getgeneratedkeys(); rs.next(); id = rs.getint(1); } catch (exception e) { system.out.println(e.getmessage()); } { dbutils.closequietly(rs); dbutils.closequietly(ps); dbutils.closequietly(conn); } return id; } }
and, lastly, database object provides connections:
import org.apache.commons.dbcp.basicdatasource; public final class database { private static final basicdatasource datasource = new basicdatasource(); static { datasource.seturl("jdbc:mysql://localhost:3306/dbname?useunicode=true&usejdbccomplianttimezoneshift=true&uselegacydatetimecode=false&servertimezone=utc"); datasource.setusername("user"); datasource.setpassword("****"); // line added debugging: sure enough, 2 objects created. datasource.setmaxactive(2); } public static connection getconnection() throws sqlexception { return datasource.getconnection(); } }
wiki
Comments
Post a Comment