Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package libepg.util.db; import java.lang.invoke.MethodHandles; import java.sql.DriverManager; import java.sql.SQLException; import loggingsupport.loggerfactory.LoggerFactory; import org.apache.commons.logging.Log; /** * * @author dosdiaopfhj */ public class JDBCAccessor implements AutoCloseable { /** * false????????????? */ public static final boolean CLASS_LOG_OUTPUT_MODE = true; private static final Log LOG; static { final Class<?> myClass = MethodHandles.lookup().lookupClass(); LOG = new LoggerFactory(myClass, JDBCAccessor.CLASS_LOG_OUTPUT_MODE).getLOG(); } private static JDBCAccessor instance; private static java.sql.Connection con = null; private JDBCAccessor() { // ?????? instance = null; } public static synchronized JDBCAccessor getInstance() { // ??????????? // ???? if (instance == null) { instance = new JDBCAccessor(); } return instance; } /** * jdbc?DB?????????? * * @author dosdiaopfhj * @see java.lang.Class.forName * @param url (DB???) * @param user DB??? * @param password DB? * */ public final synchronized void connect(String url, String user, String password) { try { this.close(); // DB? con = DriverManager.getConnection(url, user, password); LOG.trace("DB?"); } catch (SQLException ex) { con = null; LOG.fatal("DB", ex); } } /** * jdbc?DB?????????? * * @author dosdiaopfhj * @see java.lang.Class.forName * @param url (DB???) * */ public final synchronized void connect(String url) { try { this.close(); // DB? con = DriverManager.getConnection(url); LOG.trace("DB?"); } catch (SQLException ex) { con = null; LOG.fatal("DB", ex); } } /** * ?? * * @return ???null */ public final synchronized java.sql.Connection getConnection() { return con; } /** * DB?? ????????? * */ @Override public final synchronized void close() { LOG.trace("DB???"); try { if (con != null) { con.close(); LOG.trace("DB?"); } else { LOG.trace("?DB????????????"); } } catch (SQLException ex) { LOG.fatal("DB", ex); } finally { con = null; } } }