Use Java to write tool classes that control JDBC connection, execution, and shutdown _java

Source: Internet
Author: User
Tags stmt

Simple Java database connection and shutdown tool classes

People who write JDBC applications often have headaches for shutting down resources, which are boring and how to shut down with simple code, and I've written a way to relieve your pain:

 
  /** 
   * Close all closed resources 
   * 
   * @param OBJS resource objects that can be closed are connection, Statement, ResultSet, and other types of resources are automatically ignored 
  /public  static void CloseAll (Object ... objs) {for 
    (object obj:objs) { 
      if (obj instanceof Connection) Close ((Connection) obj); 
      if (obj instanceof Statement) Close ((Statement) obj); 
      if (obj instanceof ResultSet) Close ((ResultSet) obj); 
    } 
  
 

This method, with the "..." parameter, is actually a variable parameter method in Java5. It is OK to close the resource object that you want to close regardless of the order, regardless of the number of calls. For example:

catch (SQLException e) { 
      e.printstacktrace (); 
    } finally { 
      Dbtools.closeall (stmt, PSTMT1, PSTMT2, conn); 
    }


The complete writing of this class is given below:

Package Com.lavasoft.ibatistools.common; 
Import com.lavasoft.ibatistools.bean.Table; 
Import Com.lavasoft.ibatistools.metadata.DataSourceMetaData; 

Import Com.lavasoft.ibatistools.metadata.MySQLDataSourceMetaData; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import java.sql.*; 
Import java.util.List; 

Import java.util.Properties; /** * Simple Java Database connection and Shutdown tool class * * @author leizhimin 11-12-20 pm 4:32/public class DBTools {private static String dri 

  Verclassname, url, user, password; 
  static {init (); private static void Init () {InputStream in = DBTools.class.getResourceAsStream ("/com/lavasoft/ibatistools/jdbc 
    . Properties "); 
    Properties preps = new properties (); 
      try {preps.load (in); 
      Driverclassname = Preps.getproperty ("Jdbc.driver"); 
      url = preps.getproperty ("Jdbc.url"); 
      user = Preps.getproperty ("Jdbc.username"); 
    Password = preps.getproperty ("Jdbc.password"); catch (IOException e) {E.PRIntstacktrace (); /** * Create a JDBC Connection * * @return a JDBC Connection/public static Connection MakeConnection () {Co 
    Nnection conn = null; 
      try {class.forname (driverclassname); 
    conn = drivermanager.getconnection (URL, user, password); 
    catch (ClassNotFoundException e) {e.printstacktrace (); 
    catch (SQLException e) {e.printstacktrace (); 
  Return conn; 
      public static void Close (Connection conn) {if (conn!= null) try {conn.close (); 
      catch (SQLException e) {e.printstacktrace (); 
      } public static void Close (ResultSet rs) {if (Rs!= null) try {rs.close (); 
      catch (SQLException e) {e.printstacktrace (); 
      } public static void Close (Statement stmt) {if (stmt!= null) try {stmt.close (); 
      catch (SQLException e) {e.printstacktrace (); } 
  } 

  /** 
   * Close all closed resources * * @param OBJS resource objects that can be closed are connection, Statement, ResultSet, and other types of resources are automatically ignored/public static void Closeal 
      L (object.. objs) {for (object Obj:objs) {if (obj instanceof Connection) Close ((Connection) obj); 
      if (obj instanceof Statement) Close ((Statement) obj); 
    if (obj instanceof ResultSet) Close ((ResultSet) obj); 
    } public static void Main (string[] args) {Datasourcemetadata Dbmd = mysqldatasourcemetadata.instatnce (); 
    list<table> tablelist = Dbmd.getalltablemetadata (Dbtools.makeconnection ()); 
    for (table Table:tablelist) {System.out.println (table);

 } 
  } 
}


Because it is in the Write tool, the number of connections used is very small, so this is created in JDBC mode, not the connection pool. The closing method is cool, reduces the amount of code, and improves the reliability and quality of the program.


A simple JDBC Universal tool

Support a variety of databases, unified way to generate connections, optimize, the simplest way to release resources.

Welcome to the Brick!

Import Org.apache.commons.logging.Log; 

Import Org.apache.commons.logging.LogFactory; 
Import java.sql.*; 
Import java.util.List; 

Import java.util.Properties; /** * Common database operation tools, providing database connection acquisition, SQL execution, resource shutdown functions, supporting the database for oracle10g, mysql5.x. </P> * * @author leizhimin 2012-03-05 11:22/public class Dbtoolkit {private static log = LOGFACTORY.G 

  Etlog (Dbtoolkit.class); 
      static {try {Class.forName ("oracle.jdbc.driver.OracleDriver"); 
    Class.forName ("Com.mysql.jdbc.Driver"); The catch (ClassNotFoundException e) {log.error ("Load Database driver error!") 
      "); 
    E.printstacktrace (); }/** * Create a database connection * * @param URL database connection URL String * @param properties as a list of any string tag/value pairs of the connection parameters; Usually at least include " User "and" password "property * @return a JDBC database connection * @throws SQLException get connection failed to throw/public static Connection 
    MakeConnection (String URL, properties properties) throws SQLException {Connection conn = null; try {conn = drivermanager.geTconnection (URL, properties); 
      catch (SQLException e) {log.error ("Get Database connection Occurrence exception", e); 
    Throw e; 
  Return conn; /** * Execute a static SQL statement query on a database connection * * @param conn Database connection * @param staticsql static SQL statement String * @return back to check  Poll result set ResultSet object * @throws SQLException execution exception throws/public static ResultSet executequery (Connection conn, String 
    Staticsql) throws SQLException {ResultSet rs = null; 
      try {//Create object to execute SQL Statement stmt = conn.createstatement (); 
    Executes SQL and gets the return result rs = Stmt.executequery (staticsql); catch (SQLException e) {log.error ("Error executing SQL statement, please check!") 
      \ n "+ staticsql); 
    Throw e; 
  } return RS; /** * Executes a static SQL statement on a database connection * * @param conn Database connection * @param staticsql static SQL statement String * @throws Sqlex Ception is thrown when executing an exception/public static void ExecuteSQL (Connection conn, String Staticsql) throws SQLException {Sta 
    Tement stmt = null; try {//CreateExecute SQL Object stmt = conn.createstatement (); 
    Executes the SQL and gets the return result Stmt.execute (staticsql); catch (SQLException e) {log.error ("Error executing SQL statement, please check!") 
      \ n "+ staticsql); 
    Throw e; 
    Finally {close (stmt); }/** * Execute a batch of static SQL statements on a database connection * * @param conn Database connection * @param sqllist static SQL statement String Collection * @throws S Qlexception throws/public static void Executebatchsql (Connection conn, list<string> sqllist) throws Sqle when executing an exception 
      Xception {try {//Create object to execute SQL Statement stmt = conn.createstatement (); 
      for (String sql:sqllist) {stmt.addbatch (SQL); 
    //Execute SQL, and get return result Stmt.executebatch (); catch (SQLException e) {log.error ("Execute batch SQL statement error, please check!") 
      "); 
    Throw e; /** * Get Oracle data a specified sequence next value * * @param conn Database connection * @param seq_name sequence name * @r Eturn sequence Next value/public static long Sequencenextval (Connection conn, StrinG Seq_name) {long val = -1l; 
    Statement stmt = null; 
    ResultSet rs = null; 
      try {//Create object to execute SQL stmt = Conn.createstatement (); 
      Executes SQL and gets the return result rs = Stmt.executequery ("select" + Seq_name + ". Nextval from Dual"); 
    if (Rs.next ()) val = Rs.getlong (1); catch (SQLException e) {log.error ("#ERROR #: Get sequence value error, please check!) 
      \ n "+ seq_name); 
      E.printstacktrace (); 
    throw new RuntimeException (e); 
      Finally {close (RS); 
    Close (stmt); 
  return Val; /** * Closes all JDBC resources that can be turned off, regardless of sequence, always executes in the correct order * @param OBJS resource objects that can be closed are connection, Statement, ResultSet, and other types of resources automatically Slightly */public static void CloseAll (Object ... objs) {for (object Obj:objs) if (obj instanceof ResultSet 
    ) Close ((ResultSet) obj); 
    for (Object obj:objs) if (obj instanceof Statement) Close ((Statement) obj); 
  for (Object obj:objs) if (obj instanceof Connection) Close ((Connection) obj); 
}
  private static void Close (Connection conn) {if (conn!= null) try {conn.close (); The catch (SQLException e) {log.error ("Shutdown database connection exception occurred!") 
      "); 
      }} private static void Close (ResultSet rs) {if (Rs!= null) try {rs.close (); The catch (SQLException e) {log.error ("Close result set has an exception!") 
      "); 
      }} private static void Close (Statement stmt) {if (stmt!= null) try {stmt.close (); The catch (SQLException e) {log.error ("Shutdown SQL statement has an exception!) 
      ");  }/** * Test code, no use * * @param args * @throws SQLException/public static void Main (string[) args) throws SQLException {String TNS = "jdbc:oracle:thin:@\n +" (description= \ n "+" \ T (address _list =\n "+" \t\t (address= (protocol=tcp) (host=10.87.30.44) (port=1521)) \ n "+" \t\t (address= (protocol=tcp ) (host=10.87.30.45) (port=1521)) \ n "+" \t\t (address= (protocol=tcp) (Host=10.87.30.46) (port=1521) \ n "+" \t\t (Load_balance=yes) \ n "+" T) \ n "+" \ t (connect_data =\n " 
        + "\t\t (Service_name=kfcs) \ n" + "\t\t (failover_mode =\n" + "\t\t\t (type=session) \ n" + 
        \t\t\t (method=basic) \ n "+" \t\t\t (retries=5) \ n "+" \t\t\t (delay=15) \ n "+ \t\t) \ n" + 
    "\ t) \ n" + ")"; 
    Properties P_ora = new properties (); 
    P_ora.put ("User", "base"); P_ora.put ("Password", "1qaz! 
    QAZ "); 

    P_ora.put ("Internal_logon", "normal"); 
    Connection ora_conn = MakeConnection (TNS, P_ora); 
    ResultSet rs1 = Ora_conn.createstatement (). ExecuteQuery ("SELECT count (1) from Base.cfg_static_data"); 
    Rs1.next (); 
    System.out.println (Rs1.getint (1)); 
    Rs1.close (); 

    Ora_conn.close (); 
    Properties P_mysql = new properties (); 
    P_mysql.put ("User", "root"); 
    P_mysql.put ("Password", "Leizm"); 
    String url = "JDBC:MYSQL://LOCALHOST:3306/TDMC"; Connection MysQl_conn = makeconnection (URL, p_mysql); 
    ResultSet rs2 = Mysql_conn.createstatement (). ExecuteQuery ("SELECT count (1) from Cfg_code"); 
    Rs2.next (); 
    System.out.println (Rs2.getint (1)); 
    Rs2.close (); 
  Mysql_conn.close ();
 } 
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.