1.1.1 抽取一个JDBC的工具类
因为传统JDBC的开发,注册驱动,获得连接,释放资源这些代码都是重复编写的。所以可以将重复的代码提取到一个类中来完成。
[AppleScript] 纯文本查看 复制代码
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | / * * * JDBC的工具类 * @author jt * * / public class JDBCUtils { private static final String driverClassName; private static final String url ; private static final String username; private static final String password ; static { driverClassName = "com.mysql.jdbc.Driver" ; url = "jdbc:mysql:///web_test3" ; username = "root" ; password = "abc" ; } / * * * 注册驱动的方法 * / public static void loadDriver ( ) { try { Class.forName ( driverClassName ) ; } catch ( ClassNotFoundException e ) { e.printStackTrace ( ) ; } } / * * * 获得连接的方法 * / public static Connection getConnection ( ) { Connection conn = null; try { / / 将驱动一并注册 : loadDriver ( ) ; / / 获得连接 conn = DriverManager.getConnection ( url , username , password ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } return conn; } / * * * 释放资源的方法 * / public static void release ( Statement stmt , Connection conn ) { if ( stmt ! = null ) { try { stmt. close ( ) ; } catch ( SQLException e ) { e.printStackTrace ( ) ; } stmt = null; } if ( conn ! = null ) { try { conn. close ( ) ; } catch ( SQLException e ) { e.printStackTrace ( ) ; } conn = null; } } public static void release ( ResultSet rs , Statement stmt , Connection conn ) { / / 资源释放: if ( rs ! = null ) { try { rs. close ( ) ; } catch ( SQLException e ) { e.printStackTrace ( ) ; } rs = null; } if ( stmt ! = null ) { try { stmt. close ( ) ; } catch ( SQLException e ) { e.printStackTrace ( ) ; } stmt = null; } if ( conn ! = null ) { try { conn. close ( ) ; } catch ( SQLException e ) { e.printStackTrace ( ) ; } conn = null; } } } |
1.1.2 测试工具类
[AppleScript] 纯文本查看 复制代码
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | @Test / * * * 查询操作:使用工具类 * / public void demo 1 ( ) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { / / 获得连接 : conn = JDBCUtils.getConnection ( ) ; / / 创建执行SQL语句的对象 : stmt = conn.createStatement ( ) ; / / 编写SQL : String sql = "select * from user" ; / / 执行查询 : rs = stmt.executeQuery ( sql ) ; / / 遍历结果集 : while ( rs.next ( ) ) { System.out.println ( rs.getInt ( "id" ) + " " + rs.getString ( "username" ) + " " + rs.getString ( "password" ) ) ; } } catch ( Exception e ) { e.printStackTrace ( ) ; } finally { / / 释放资源 : JDBCUtils.release ( rs , stmt , conn ) ; } } |