规范和封装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
 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

 

转载于:https://www.cnblogs.com/aineko/p/3895990.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值