1 PackageCom.lhy.jdbc.util;2 3 ImportJava.net.URL;4 ImportJava.sql.*;5 6 /**7 * JDBC Tool class, General tool class final. 8 * Tool classes generally do not require new and do not need to construct an instance. (The construction method is private) others will not be new. 9 * methods for using classes at this time:Ten * 1 is a singleton mode (complex point) One * 2 is to provide a static public method. (Simple) A * This example is implemented simply by providing the public method. Requires a static method - * - * @authorhy the * - */ - Public Final classJdbcutil { - Private StaticString url = "Jdbc:mysql://localhost:3306/bbs"; + Private StaticString user = "root"; - Private StaticString PassWord = "root"; + A //The construction method is private, others cannot be constructed, and there are no instances. at PrivateJdbcutil () { - - } - - /** - * Static code blocks, classes loaded into the virtual machine are only executed once. in */ - Static { to Try { +Class.forName ("Com.mysql.jdbc.Driver"); -}Catch(ClassNotFoundException e) { the * e.printstacktrace (); $ }Panax Notoginseng - } the + Public StaticConnection getconnection () { AConnection conn =NULL; the Try { +conn =drivermanager.getconnection (Url,user,password); -}Catch(SQLException e) { $ $ e.printstacktrace (); - } - returnConn; the - Wuyi the } - Wu //frees resources, overloads methods. - Public Static voidClose (Connection conn) { About Try { $ if(Conn! =NULL){ - conn.close (); -conn =NULL; - } A}Catch(SQLException e) { + e.printstacktrace (); the } - } $ Public Static voidClose (Statement stmt) { the Try{ the if(stmt! =NULL){ the stmt.close (); thestmt =NULL; - } in}Catch(SQLException e) { the e.printstacktrace (); the } About } the Public Static voidClose (ResultSet rs) { the Try{ the if(rs! =NULL){ + rs.close (); -rs =NULL; the }Bayi}Catch(SQLException e) { the e.printstacktrace (); the } - } -}
JDBC Connection Database Tool class