JDBC学习笔记——简单UerDao

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

 

1、JDBCUtils(产生Connection,关闭资源)

  1 package com.sina.jdbc;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.IOException;
  6 import java.io.FileNotFoundException;
  7 import java.util.Properties;
  8 import java.sql.Connection;
  9 import java.sql.DriverManager;
 10 import java.sql.Statement;
 11 import java.sql.ResultSet;
 12 import java.sql.SQLException;
 13 
 14 public class JDBCUtils {
 15     private JDBCUtils(){
 16 
 17     }
 18 
 19     public static JDBCUtils getInstance(){
 20         if(instance == null){
 21             synchronized(JDBCUtils.class){
 22                 if(instance == null){       //二次判空, 防止多线程下多次创建实例对象
 23                     instance = new JDBCUtils();
 24                 }
 25             }
 26         }
 27         return instance;
 28     }
 29 
 30     public Connection getConnection(){
 31         Connection connection = null;
 32         try {
 33             connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
 34         } catch(SQLException e){
 35             e.printStackTrace();
 36         }
 37         return connection;
 38     }
 39 
 40     public void close(Connection connection, Statement stmt, ResultSet rs){
 41         if(rs != null){
 42             try {
 43                 rs.close();
 44             } catch(SQLException e){
 45                 e.printStackTrace();
 46             }
 47         }
 48 
 49         if(stmt != null){
 50             try {
 51                 stmt.close();
 52             } catch(SQLException e){
 53                 e.printStackTrace();
 54             }
 55         }
 56 
 57         if(connection != null){
 58             try {
 59                 connection.close();
 60             } catch(SQLException e){
 61                 e.printStackTrace();
 62             }
 63         }
 64     }
 65 
 66     private static JDBCUtils instance = null;
 67     //加载配置文件, 读取以下信息以建立Connection
 68     private static String DRIVER_NAME;
 69     private static String URL;
 70     private static String USER_NAME;
 71     private static String PASSWORD;
 72     static {
 73         FileInputStream fis = null;
 74         try {
 75             Properties p = new Properties();
 76             File file = new File("./src/config.properties");
 77             fis = new FileInputStream(file);
 78             p.load(fis);
 79             DRIVER_NAME = p.getProperty("DRIVER_NAME");
 80             URL = p.getProperty("URL");
 81             USER_NAME = p.getProperty("USER_NAME");
 82             PASSWORD = p.getProperty("PASSWORD");
 83 
 84             Class.forName(DRIVER_NAME);  //加载驱动
 85         } catch(ClassNotFoundException e) {
 86             System.out.println(DRIVER_NAME + "驱动类找不着.");
 87         } catch(FileNotFoundException e) {
 88             System.out.println("文件 config.properties 找不到.");
 89         } catch(IOException e){
 90             e.printStackTrace();
 91         } finally{
 92             if(fis != null){
 93                 try {
 94                     fis.close();
 95                 } catch(IOException e){
 96                     e.printStackTrace();
 97                 }
 98             }
 99         }
100     }
101 }
View Code

2、UserDao

 1 package com.sina.jdbc.dao;
 2 
 3 import com.sina.jdbc.orm.User;
 4 
 5 //UserDao(User数据访问对象)利用接口实现,属面向接口编程,方便代码使用和管理,若实现类被修改,使用接口方法的程序不受影响,不需修改
 6 public interface UserDao {
 7     void addUser(User user);
 8     void deleteUser(User user);
 9     void updateUser(User user);
10     User getUser(Integer id);
11     User findUser(String name, String gender);
12 }
View Code

3、UserDaoFactory

 1 package com.sina.jdbc.dao;
 2 
 3 import java.util.Properties;
 4 import java.io.InputStream;
 5 import java.io.IOException;
 6 
 7 //使用DAD工厂实现,若要改用其他方式实现的UserDao,则直接修改配置文件即可,程序用到UserDao的地方无需修改
 8 public class UserDaoFactory {
 9     private UserDaoFactory(){
10 
11     }
12 
13     public static UserDaoFactory getInstance(){
14         if(instance == null){
15             synchronized(UserDaoFactory.class){
16                 if(instance == null){
17                     instance = new UserDaoFactory();
18                 }
19             }
20         }
21         return instance;
22     }
23 
24     public UserDao getUserDao(){
25         UserDao retVal = null;
26         Properties p = new Properties();
27         InputStream is = null;
28         try {
29            is = UserDaoFactory.class.getClassLoader().getResourceAsStream("config.properties");
30            p.load(is);
31            String daoClassName = p.getProperty("daoClassName");
32            retVal = (UserDao)Class.forName(daoClassName).getConstructor().newInstance();
33         } catch(Exception e){
34             throw new ExceptionInInitializerError();
35         } finally{
36             if(is != null){
37                 try {
38                     is.close();
39                 } catch(IOException e){
40                     e.printStackTrace();
41                 }
42             }
43         }
44         return retVal;
45     }
46 
47     private static UserDaoFactory instance = null;
48 }
View Code

4、UserDao(增删改查)

  1 package com.sina.jdbc.dao.imp;
  2 
  3 import com.sina.jdbc.dao.UserDao;
  4 import com.sina.jdbc.dao.DAOException;
  5 import com.sina.jdbc.orm.User;
  6 import com.sina.jdbc.JDBCUtils;
  7 import java.sql.*;
  8 
  9 public class UserDaoJdbcImp implements UserDao {
 10     @Override
 11     public void addUser(User user) {
 12         Connection connection = null;
 13         PreparedStatement pstmt = null;
 14         try {
 15             connection = JDBCUtils.getInstance().getConnection();
 16             pstmt = connection.prepareStatement("insert into t_user values(?, ?, ?, ?, ?)");
 17             setPstmt(pstmt, user);
 18             pstmt.execute();
 19         } catch(SQLException e){
 20             throw new DAOException(e.getMessage(), e);  //抛出异常给上级调用者, 让得知异常发生
 21         } finally{
 22             JDBCUtils.getInstance().close(connection, pstmt, null);
 23         }
 24     }
 25 
 26     @Override
 27     public void deleteUser(User user){
 28         Connection connection = null;
 29         PreparedStatement pstmt = null;
 30         try {
 31             connection = JDBCUtils.getInstance().getConnection();
 32             pstmt = connection.prepareStatement("delete from t_user where id = ? and name = ?");
 33             pstmt.setInt(1, user.getId());
 34             pstmt.setString(2, user.getName());
 35             pstmt.execute();
 36         } catch(SQLException e){
 37             throw new DAOException(e.getMessage(), e);
 38         } finally{
 39             JDBCUtils.getInstance().close(connection, pstmt, null);
 40         }
 41     }
 42 
 43     @Override
 44     public void updateUser(User user){
 45         Connection connection = null;
 46         PreparedStatement pstmt = null;
 47         try {
 48             connection = JDBCUtils.getInstance().getConnection();
 49             pstmt = connection.prepareStatement("update t_user set id = ?, name = ?, birthday = ?, gender = ?, property = ? where id = ?");
 50             setPstmt(pstmt, user);
 51             pstmt.setInt(6, user.getId());
 52             pstmt.execute();
 53         } catch(SQLException e){
 54             throw new DAOException(e.getMessage(), e);
 55         } finally{
 56             JDBCUtils.getInstance().close(connection, pstmt, null);
 57         }
 58     }
 59 
 60     @Override
 61     public User getUser(Integer id){
 62         Connection connection = null;
 63         PreparedStatement pstmt = null;
 64         ResultSet rs = null;
 65         User user = null;
 66         try {
 67             connection = JDBCUtils.getInstance().getConnection();
 68             pstmt = connection.prepareStatement("select id,name,birthday,gender,property from t_user where id = ?");
 69             pstmt.setInt(1, id);
 70             rs = pstmt.executeQuery();
 71             user = createUser(rs);
 72         } catch(SQLException e){
 73             throw new DAOException(e.getMessage(), e);
 74         } finally{
 75             JDBCUtils.getInstance().close(connection, pstmt, rs);
 76         }
 77         return user;
 78     }
 79 
 80     @Override
 81     public User findUser(String name, String gender){
 82         Connection connection = null;
 83         PreparedStatement pstmt = null;
 84         ResultSet rs = null;
 85         User user = null;
 86         try {
 87             connection = JDBCUtils.getInstance().getConnection();
 88             pstmt = connection.prepareStatement("select id,name,birthday,gender,property from t_user where name = ? and gender = ?");
 89             pstmt.setString(1, name);
 90             pstmt.setString(2, gender);
 91             rs =  pstmt.executeQuery();
 92             user = createUser(rs);
 93         } catch(SQLException e){
 94             throw new DAOException(e.getMessage(), e);
 95         } finally{
 96             JDBCUtils.getInstance().close(connection, pstmt, rs);
 97         }
 98         return user;
 99     }
100 
101     private User createUser(ResultSet rs) throws SQLException {
102         User user = null;
103         while(rs.next()){
104             user = new User(rs.getInt("id"), rs.getString("name"), rs.getDate("birthday"), rs.getString("gender"), rs.getFloat("property"));
105         }
106         return user;
107     }
108 
109     private static void setPstmt(PreparedStatement pstmt, User user) throws SQLException {
110         pstmt.setInt(1, user.getId());
111         pstmt.setString(2, user.getName());
112         pstmt.setDate(3, new Date(user.getBirthday().getTime()));
113         pstmt.setString(4, user.getGender());
114         pstmt.setFloat(5, user.getProperty());
115     }
116 }
View Code

5、User

 1 package com.sina.jdbc.orm;
 2 
 3 import java.util.Date;
 4 
 5 //ORM(对象关系映射),数据二维表对应Java类,表字段对应类属性
 6 public class User {
 7     public User(){
 8 
 9     }
10 
11     public User(Integer id, String name, Date birthday, String gender, Float property){
12         this.id = id;
13         this.name = name;
14         this.birthday = birthday;
15         this.gender = gender;
16         this.property = property;
17     }
18 
19     public void setId(Integer id){
20         this.id = id;
21     }
22 
23     public Integer getId(){
24         return id;
25     }
26 
27     public void setName(String name){
28         this.name = name;
29     }
30 
31     public String getName(){
32         return name;
33     }
34 
35     public void setBirthday(Date birthday){
36         this.birthday = birthday;
37     }
38 
39     public Date getBirthday(){
40         return birthday;
41     }
42 
43     public void setGender(String gender) {
44         this.gender = gender;
45     }
46 
47     public String getGender(){
48         return gender;
49     }
50 
51     public void setProperty(Float property){
52         this.property = property;
53     }
54 
55     public Float getProperty(){
56         return property;
57     }
58 
59     private Integer id;       //采用包装类,如果id为主键并自增长,在插入数据库时可不指定id,
60     // 若以PreparedStatement返回主键并给相应的User对象赋值,就可以区别哪些个对象已经写到数据库中,因为已经保存过的对象会得到返回的主键并赋值给id,
61     // 而没被操作的对象id属性将为null,而不是数字0,易于区分
62     private String name;
63     private Date birthday;
64     private String gender;
65     private Float property;
66 }
View Code

6、DAOException(给上级调用者抛出异常,让其得知异常产生地点)

 1 package com.sina.jdbc.dao;
 2 
 3 public class DAOException extends RuntimeException {
 4     public DAOException() {
 5     }
 6 
 7     public DAOException(String message) {
 8         super(message);
 9     }
10 
11     public DAOException(String message, Throwable cause) {
12         super(message, cause);
13     }
14 
15     public DAOException(Throwable cause) {
16         super(cause);
17     }
18 }
View Code

有无DAOException时报告异常对比.

DAOException:

JDBC学习笔记——简单UerDao_第1张图片

SQLException:

JDBC学习笔记——简单UerDao_第2张图片

7、Test

 1 package com.sina.jdbc;
 2 
 3 import com.sina.jdbc.dao.UserDao;
 4 import com.sina.jdbc.dao.UserDaoFactory;
 5 import com.sina.jdbc.orm.User;
 6 import java.util.Date;
 7 
 8 public class Test {
 9     public static void main(String[] args){
10         UserDao userDao = UserDaoFactory.getInstance().getUserDao();
11         User user = new User(10, "Tom", new Date(), "男", 230f);
12         userDao.addUser(user);
13 //        User user = userDao.findUser("Tom", "男");
14 //        System.out.println(user.getId()+ " " + user.getBirthday());
15 //        userDao.deleteUser(user);
16     }
17 }
View Code

 

  以下代码为简单的UserDAO,本人为JAVA新人,发布出来方便以后复习。另外,其中可能存在一些不足的地方,如有建议,请告知。

转载于:https://www.cnblogs.com/Hr666/p/10307570.html

你可能感兴趣的:(JDBC学习笔记——简单UerDao)