JDBC is a necessary tool to connect to a database, but each time the connection is to be re-written again too cumbersome, and not conducive to the readability of the code, here is a tool class to encapsulate.
1 Packagecom.gh;2 3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 ImportJava.sql.ResultSet;6 Importjava.sql.SQLException;7 Importjava.sql.Statement;8 ImportJava.util.ResourceBundle;9 Ten /** One * Note the first driver package ..... A * - * @authorGanhang - * the */ - Public classJdbcutil { - //Driver Class - Public StaticString Driver; + //Database Address - Public StaticString URL; + //Database user name A Public StaticString user; at //Database Password - Public StaticString password; - //just restart with configuration file changes - Public StaticResourceBundle RB = Resourcebundle.getbundle ("Com.gh.jdbc_config"); - Static { -Driver = rb.getstring ("jdbc. Driver "); inurl = rb.getstring ("Jdbc.url"); -user = Rb.getstring ("Jdbc.user"); toPassword = rb.getstring ("Jdbc.password"); + Try { - Class.forName (Driver); the}Catch(ClassNotFoundException e) { * e.printstacktrace (); $ }Panax Notoginseng } - the //Prevention of instantiation + PrivateJdbcutil () {} A the Public StaticConnection getconnection () { +Connection conn =NULL; - Try { $conn =drivermanager.getconnection (URL, user, password); $}Catch(SQLException e) { - e.printstacktrace (); -System.out.println ("Connection failed! "); the } - returnConn;Wuyi } the - Public Static voidClose (ResultSet RS, Statement S, Connection c) { Wu Try { - if(rs! =NULL) About rs.close (); $ if(s! =NULL) - s.close (); - if(c! =NULL) - c.close (); A}Catch(Exception e) { + e.printstacktrace (); the } - } $}
1 Packagecom.gh;2 3 Importjava.sql.Connection;4 Importjava.sql.PreparedStatement;5 ImportJava.sql.ResultSet;6 Importjava.sql.SQLException;7 /**8 * Test9 * @authorGanhangTen * One */ A Public classTest { - Public Static voidMain (string[] args) { -Connection conn=jdbcutil.getconnection (); theString sql= "SELECT * FROM Test"; - Try { -PreparedStatement ps=conn.preparestatement (SQL); -ResultSet rs=ps.executequery (); + while(Rs.next ()) { -System.out.println (Rs.getint (1)); + } A Jdbcutil.close (RS, PS, conn); at}Catch(SQLException e) { - e.printstacktrace (); - } - - } -}
1 jdbc. Driver=oracle.jdbc.oracledriver2jdbc.url=jdbc:oracle:thin: @localhost: 1521:ORCL3 Jdbc.user=scott4 jdbc.password=.
configuration file
Java Learning JDBC Encapsulation