规范和封装jdbc程序代码

JDBC 部分方法引用工具类

规范和封装jdbc程序代码
 1 package it.cast.jdbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Statement;
 8 
 9 public class jdbcUtils {
10 
11     private static String url = "jdbc:mysql://localhost:3306/jdbc";
12     private static String user = "root";
13     private static String password = "123";
14 
15     private jdbcUtils() {
16 
17     }
18 
19     static {
20         try {
21             Class.forName("com.mysql.jdbc.Driver");
22         } catch (ClassNotFoundException e) {
23             e.printStackTrace();
24         }
25     }
26 
27     public static Connection getConnection() throws SQLException {
28         return DriverManager.getConnection(url, user, password);
29     }
30 
31     public static void free(ResultSet rs, Statement st, Connection conn) {
32 
33         try {
34             if (rs != null)
35                 rs.close();
36         } catch (SQLException e) {
37             e.printStackTrace();
38         } finally {
39 
40             try {
41                 if (st != null)
42                     st.close();
43             } catch (SQLException e) {
44                 e.printStackTrace();
45             } finally {
46 
47                 try {
48                     if (conn != null)
49                         conn.close();
50                 } catch (SQLException e) {
51                     e.printStackTrace();
52                 }
53             }
54 
55         }
56 
57     }
58 }
jdbcUtils
规范和封装jdbc程序代码
 1 package it.cast.jdbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7 
 8 public class Base {
 9     
10     static Connection conn = null;
11 
12     public static void main(String[] args) throws SQLException, ClassNotFoundException {
13          test();
14     }
15 
16     static void test() throws SQLException, ClassNotFoundException {
17         
18 
19         // 2.建立连接
20         conn = jdbcUtils.getConnection();
21 
22         // 3.创建语句
23         Statement st = conn.createStatement();
24 
25         // 4.执行语句
26         ResultSet rs = st.executeQuery("select * from user");
27 
28         // 5.处理结果
29         while (rs.next()) {
30             System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t"
31                     + rs.getObject(3)+"\t" + rs.getObject(4));
32         }
33         
34         //6.释放资源
35         jdbcUtils.free(rs, st, conn);
36     }
37 
38 }
Base

 

规范和封装jdbc程序代码,布布扣,bubuko.com

规范和封装jdbc程序代码

上一篇:数据库基本操作


下一篇:Oracle 监听器无法启动(TNS-12537,TNS-12560,TNS-00507)