Jdbcutils.java Toolkit:
1 PackageCom.xxyh.jdbc;2 Importjava.sql.Connection;3 ImportJava.sql.DriverManager;4 ImportJava.sql.ResultSet;5 Importjava.sql.SQLException;6 Importjava.sql.Statement;7 Public classJdbcutils {8 9 Private Static FinalString url = "Jdbc:mysql://localhost:3306/jdbc";Ten Private Static FinalString user = "root"; One Private Static FinalString password = "1234"; A - Privatejdbcutils () { - } the - Static { - Try { - //placing the registration driver in a static code block is performed only once +Class.forName ("Com.mysql.jdbc.Driver"); -}Catch(ClassNotFoundException e) { + Throw NewExceptionininitializererror (e); A } at } - - Public StaticConnection getconnection ()throwsSQLException { - returndrivermanager.getconnection (URL, user, password); - } - in Public Static voidClose (ResultSet rs, Statement stmt, Connection conn) { - Try { to if(rs! =NULL) { + rs.close (); - } the}Catch(SQLException e) { * e.printstacktrace (); $}finally {Panax Notoginseng Try { - if(stmt! =NULL) { the stmt.close (); + } A}Catch(SQLException e) { the e.printstacktrace (); +}finally { - if(Conn! =NULL) { $ Try { $ conn.close (); -}Catch(SQLException e) { - e.printstacktrace (); the } - }Wuyi } the } - } Wu}
Test Kit is useful:
1 Packagecom.xxyh.jdbc.test;2 Importjava.sql.Connection;3 ImportJava.sql.ResultSet;4 Importjava.sql.SQLException;5 Importjava.sql.Statement;6 Importcom.xxyh.jdbc.JdbcUtils;7 Public classJdbcutilstest {8 Public Static voidMain (string[] args)throwsSQLException {9Connection conn =NULL;TenStatement stmt =NULL; OneResultSet rs =NULL; A - Try { -conn =jdbcutils.getconnection (); thestmt =conn.createstatement (); -rs = Stmt.executequery ("SELECT * from User"); - - while(Rs.next ()) { +System.out.println (Rs.getobject ("id") + "\ T" + rs.getobject ("name") + "\ T" + -Rs.getobject ("Birthday") + "\ T" + rs.getobject ("Money"))); + } A}finally { at Jdbcutils.close (RS, stmt, conn); - } - } -}
"Run Results": 1 zhangs 1985-01-01 100.02 Lisi 1986-01-01 200.03 Wangwu 1987-01-01 300.0
JDBC Learning Note (3): Self-build toolkit