JDBC(一)

2020-01-23 16:01:36来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

JDBC(一)

1.   JDBC介绍

JDBC(Java DataBase Connectivity),即Java数据库的连接。JDBC是一种用于执行SQL语句(DML,DDL,DQL)的Java API,可以为多种关系数据库(oracle,mysql,sqlserver)提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。

Java 通过JDBC访问数据库,数据库厂家有很多,如Mysql、Oracle、SqlServer等,而JDBC提供了操作这些数据库的统一的接口、基准,让各大厂商去实现这组规范。各大数据库厂商只需要提供对应的JDBC的jar包,使java代码通过不同厂商实现的jar包访问对应的数据库。

 

2.   JDBC完成CRUD规范步骤

2.1.规范DAO层的实现

DAO层:涉及到开发中的三层架构与MVC层级结构。DAO层叫数据访问层,全称data access object,属于一种比较底层、比较基础的操作,具体作用于某个表、某个实体的增删改查。

 

DAO层的创建规范:

这里包括界面层传入数据封装成为的域对象——Domain类对象

 

2.2. DAO层具体实现

具体代码如下:

DAO层:

接口:

 1 public interface IStudentDao {
 2 
 3     public void insert(Student student);
 4 
 5     public void update(Student student);
 6 
 7     public void delete(Integer id);
 8 
 9     public Student queryOne(Integer id);
10 
11     public List<Student> queryAll();
12 }

实现类Impl:

  1 package cn.yif.dao.impl;
  2 
  3 import cn.yif.domain.Student;
  4 import cn.yif.dao.IStudentDao;
  5 import cn.yif.utils.JDBCUtil;
  6 
  7 import java.sql.*;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 
 11 /**
 12  * @author Administrator
 13  * @create 2019-09-13-20:33
 14  */
 15 public class StudentDaoImpl implements IStudentDao {
 16     @Override
 17     public void insert(Student student) {
 18         Connection conn = null;
 19         Statement statement = null;
 20         try {
 21             //①加载(注册)驱动,这部分硬编码可以写也可以不写,jdbc4.0版本自带了
 22             //Class.forName("com.mysql.jdbc.Driver");
 23             //②获取连接
 24             //conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest01", "root", "admin");
 25             conn = JDBCUtil.getInstance().getConnection();
 26             //③获取语句对象:用来执行SQL语句
 27             statement = conn.createStatement();
 28             //④执行SQL语句
 29             String insertSql = "insert into jdbcdemo01 (name, age) values ('"+student.getName()+"', "+student.getAge()+")";
 30             statement.execute(insertSql);
 31         }catch (Exception ex){
 32             ex.printStackTrace();
 33         }finally {
 34             //⑤释放资源
 35             JDBCUtil.getInstance().close(null, statement, conn);
 36         }
 37     }
 38 
 39     @Override
 40     public void update(Student student) {
 41         Connection conn = null;
 42         Statement statement = null;
 43         try {
 44             //①加载(注册)驱动
 45             //Class.forName("com.mysql.jdbc.Driver");
 46             //②获取连接
 47             //conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest01", "root", "admin");
 48             conn = JDBCUtil.getInstance().getConnection();
 49             //③获取语句对象:用来执行SQL语句
 50             statement = conn.createStatement();
 51             //④执行SQL语句
 52             String updateSql = "update jdbcdemo01 set name = '"+student.getName()+"', age = "+student.getAge()+" where id = "+student.getId()+"";
 53             statement.execute(updateSql);
 54         }catch (Exception ex){
 55             ex.printStackTrace();
 56         }finally {
 57             //⑤释放资源
 58             JDBCUtil.getInstance().close(null, statement, conn);
 59         }
 60     }
 61 
 62     @Override
 63     public void delete(Integer id) {
 64         Connection conn = null;
 65         Statement statement = null;
 66         try {
 67             //①加载(注册)驱动
 68             //Class.forName("com.mysql.jdbc.Driver");
 69             //②获取连接
 70             //conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest01", "root", "admin");
 71             conn = JDBCUtil.getInstance().getConnection();
 72             //③获取语句对象:用来执行SQL语句
 73             statement = conn.createStatement();
 74             //④执行SQL语句
 75             String deleteSql = "delete from jdbcdemo01 where id = "+ id +"";
 76             statement.execute(deleteSql);
 77         }catch (Exception ex){
 78             ex.printStackTrace();
 79         }finally {
 80             //⑤释放资源
 81             JDBCUtil.getInstance().close(null, statement, conn);
 82         }
 83     }
 84 
 85     @Override
 86     public Student queryOne(Integer id) {
 87         Connection conn = null;
 88         Statement statement = null;
 89         ResultSet resultSet = null;
 90         Student student = null;
 91         try {
 92             //①加载(注册)驱动
 93             //Class.forName("com.mysql.jdbc.Driver");
 94             //②获取连接
 95             //conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest01", "root", "admin");
 96             conn = JDBCUtil.getInstance().getConnection();
 97             //③获取语句对象:用来执行SQL语句
 98             statement = conn.createStatement();
 99             //④执行SQL语句
100             String queryOneSql = "select * from jdbcdemo01 where id = "+ id +"";
101             resultSet = statement.executeQuery(queryOneSql);
102             if(resultSet.next())
103             {
104                 student = new Student();
105                 student.setId(resultSet.getInt("id"));
106                 student.setName(resultSet.getString("name"));
107                 student.setAge(resultSet.getInt("age"));
108             }
109         }catch (Exception ex){
110 
111         }finally {
112             //⑤释放资源
113             JDBCUtil.getInstance().close(resultSet, statement, conn);
114         }
115         return student;
116     }
117 
118     @Override
119     public List<Student> queryAll() {
120         Connection conn = null;
121         Statement statement = null;
122         ResultSet resultSet = null;
123         Student student = null;
124         List<Student> list = new ArrayList<Student>();
125         try {
126             //①加载(注册)驱动
127             //Class.forName("com.mysql.jdbc.Driver");
128             //②获取连接
129             //conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest01", "root", "admin");
130             conn = JDBCUtil.getInstance().getConnection();
131             //③获取语句对象:用来执行SQL语句
132             statement = conn.createStatement();
133             //④执行SQL语句
134             String queryAllSql = "select * from jdbcdemo01";
135             resultSet = statement.executeQuery(queryAllSql);
136             while (resultSet.next())
137             {
138                 student = new Student();
139                 student.setId(resultSet.getInt("id"));
140                 student.setName(resultSet.getString("name"));
141                 student.setAge(resultSet.getInt("age"));
142                 list.add(student);
143             }
144         }catch (Exception ex){
145             ex.printStackTrace();
146         }finally {
147             //⑤释放资源
148             JDBCUtil.getInstance().close(resultSet, statement, conn);
149         }
150         return list;
151     }
152 }

 

Domain层:

 1 package cn.yif.domain;
 2 
 3 /**
 4  * @author Administrator
 5  * @create 2019-09-13-20:23
 6  */
 7 public class Student {
 8     //ID表示编号
 9     private Integer id;
10 
11     //name表示名字
12     private String name;
13 
14     //age表示年龄
15     private Integer age;
16 
17     public Integer getId() {
18         return id;
19     }
20 
21     public void setId(Integer id) {
22         this.id = id;
23     }
24 
25     public String getName() {
26         return name;
27     }
28 
29     public void setName(String name) {
30         this.name = name;
31     }
32 
33     public Integer getAge() {
34         return age;
35     }
36 
37     public void setAge(Integer age) {
38         this.age = age;
39     }
40 
41     public Student() {
42     }
43 
44     public Student(Integer id, String name, Integer age) {
45         this.id = id;
46         this.name = name;
47         this.age = age;
48     }
49 
50     @Override
51     public String toString() {
52         return "Student{" +
53                 "id=" + id +
54                 ", name='" + name + '\'' +
55                 ", age=" + age +
56                 '}';
57     }
58 }

 

工具类JDBCUtil实现:

 1 package cn.yif.utils;
 2 
 3 import java.io.IOException;
 4 import java.sql.*;
 5 import java.util.Properties;
 6 
 7 /**
 8  * @author Administrator
 9  * @create 2019-09-13-21:21
10  */
11 public class JDBCUtil {
12     //使用静态static类构造单例模式
13     private JDBCUtil(){ }
14     //在静态代码块中创建instance的实例,这里使用static静态变量来保存
15     private static JDBCUtil instance = null;
16     //每次都要加载驱动,这里定义一个Properties,把资源文件里面的内容读到Properties里面
17     private static Properties properties = null;
18     //JDBCUtil类加载的时候,就加载注册驱动
19     static {
20         properties = new Properties();
21         try {
22             //当前线程类加载器加载获取properties文件
23             properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
24             try {
25                 Class.forName(properties.getProperty("driverClassName"));
26             } catch (ClassNotFoundException e) {
27                 e.printStackTrace();
28             }
29         } catch (IOException e) {
30             e.printStackTrace();
31         }
32 
33         instance = new JDBCUtil();
34     }
35 
36     public static JDBCUtil getInstance(){
37         return instance;
38     }
39 
40     //抽取获取连接Connection的方法
41     public Connection getConnection() throws SQLException {
42        return DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
43     }
44 
45     //抽取JDBC关闭资源的close方法
46     public void close(ResultSet resultSet, Statement statement, Connection conn){
47         try {
48             if(resultSet != null){
49                 resultSet.close();
50             }
51         } catch (SQLException e) {
52             e.printStackTrace();
53         }
54         try {
55             if(statement != null){
56                 statement.close();
57             }
58         } catch (SQLException e) {
59             e.printStackTrace();
60         }
61         try {
62             if(conn != null){
63                 conn.close();
64             }
65         } catch (SQLException e) {
66             e.printStackTrace();
67         }
68     }
69 }

 

JDBC资源配置文件:

1 driverClassName = com.mysql.jdbc.Driver
2 url = jdbc:mysql://localhost:3306/jdbctest01
3 username = root
4 password = admin

 

或GitHub:https://github.com/devyf/JavaWorkSpace/tree/master/JDBC_0913_01


原文链接:https://www.cnblogs.com/yif0118/p/12230527.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Java框架之SpringMVC 05-拦截器-异常映射-Spring工作流程

下一篇:SpringBoot学习笔记一