Java中JDBC工具类封装

Java中JDBC的封装

Java使用JDBC连接数据库可以概括分为六步:

1、注册驱动
2、获取连接对象
3、获取数据库操作对象
4、执行SQL语句
5、处理查询结果集
6、释放资源

 1 public class JDBCUtil {
 2     //连接对象
 3     private Connection connection = null;
 4     //数据库操作对象
 5     private PreparedStatement ps = null;
 6     //数据库连接地址
 7     private static String url = "jdbc:mysql://localhost:3306/";
 8     //用户名
 9     private static String user = "root";
10     //密码
11     private static String password = "123456";
12 //静态代码块 注册驱动 13 //类加载的时候,只执行一次 14 static{ 15 try { 16 Class.forName("com.mysql.jdbc.Driver"); 17 } catch (ClassNotFoundException e) { 18 e.printStackTrace(); 19 } 20 } 21 22 //获取连接对象 23 public Connection getConnection(){ 24 //Connection conn = null; 25 try { 26 connection = DriverManager.getConnection(url,user,password); 27 } catch (SQLException e) { 28 e.printStackTrace(); 29 System.out.println("数据库连接失败...."); 30 } 31 System.out.println("数据库连接成功..."); 32 return connection; 33 } 34 35 //获取数据库操作对象 36 public PreparedStatement createPreparedStatement(String sql){ 37 connection = getConnection(); 38 try { 39 ps = connection.prepareStatement(sql); 40 } catch (SQLException e) { 41 e.printStackTrace(); 42 } 43 return ps; 44 } 45 46 //释放资源 47 public void close(){ 48 //释放连接对象 49 if (connection != null) { 50 try { 51 connection.close(); 52 } catch (SQLException e) { 53 e.printStackTrace(); 54 } 55 } 56 //释放数据库操作对象 57 if (ps != null) { 58 try { 59 ps.close(); 60 } catch (SQLException e) { 61 e.printStackTrace(); 62 } 63 } 64 System.out.println("释放资源成功..."); 65 } 66 //方法的重载 67 public void close(ResultSet reuslt){ 68 // 调用释放资源的方法 69 close(); 70 // 释放查询结果集对象 71 if (reuslt != null) { 72 try { 73 reuslt.close(); 74 } catch (SQLException e) { 75 e.printStackTrace(); 76 } 77 } 78 } 79 80 }
原文地址:https://www.cnblogs.com/mcxfate/p/13405082.html