JDBC学习笔记(3):自建工具包

JdbcUtils.java工具包:

 1 package com.xxyh.jdbc;
 2 import java.sql.Connection;
 3 import java.sql.DriverManager;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7 public class JdbcUtils {
 8     
 9     private static final String url = "jdbc:mysql://localhost:3306/jdbc";
10     private static final String user = "root";
11     private static final String password = "1234";
12     
13     private JdbcUtils() {
14     }
15     
16     static {
17         try {
18             // 将注册驱动放在静态代码块中只需执行一次
19             Class.forName("com.mysql.jdbc.Driver");
20         } catch(ClassNotFoundException e) {
21             throw new ExceptionInInitializerError(e);
22         } 
23     }
24     
25     public static Connection getConnection() throws SQLException {
26         return DriverManager.getConnection(url, user, password);
27     }
28     
29     public static void close(ResultSet rs, Statement stmt, Connection conn) {
30         try {
31             if (rs != null) {
32                 rs.close();
33             }
34         } catch (SQLException e) {
35             e.printStackTrace();
36         } finally {
37             try {
38                 if (stmt != null) {
39                     stmt.close();
40                 }
41             } catch (SQLException e) {
42                 e.printStackTrace();
43             } finally {
44                 if (conn != null) {
45                     try {
46                         conn.close();
47                     } catch (SQLException e) {
48                         e.printStackTrace();
49                     }
50                 }
51             }
52         }
53     }
54 }
测试工具包是否有用:
 1 package com.xxyh.jdbc.test;
 2 import java.sql.Connection;
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.sql.Statement;
 6 import com.xxyh.jdbc.JdbcUtils;
 7 public class JdbcUtilsTest {
 8     public static void main(String[] args) throws SQLException {
 9         Connection conn = null;
10         Statement stmt = null;
11         ResultSet rs = null;
12         
13         try { 
14             conn = JdbcUtils.getConnection();
15             stmt = conn.createStatement();
16             rs = stmt.executeQuery("select * from user");
17             
18             while (rs.next()) {
19                 System.out.println(rs.getObject("id") + "\t" + rs.getObject("name") + "\t" +
20                         rs.getObject("birthday") + "\t" + rs.getObject("money"));
21             }
22         } finally {
23             JdbcUtils.close(rs, stmt, conn);
24         }
25     }
26 }
【运行结果】:
1    zhangs    1985-01-01    100.0
2    lisi      1986-01-01    200.0
3    wangwu    1987-01-01    300.0  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。