DAO是Data Access Object数据访问接口,数据访问:顾名思义就是与数据库打交道。夹在业务逻辑与数据库资源中间。
在连接数据库过程当中,可以定义一个DAO接口,然后编写一个类来扩展这个DAO类来实现DAO接口中的方法。如:有一个用户表t_user:id(int) , username(varchar(255)) , password(varchar(255))
定义一个简单的JAVA类(VO):User
1package cn.zhang.org.vo;
2
3public class User {
4 private String username;
5 private String password;
6 public String getUsername() {
7 return username;
8 }
9 public void setUsername(String username) {
10 this.username = username;
11 }
12 public String getPassword() {
13 return password;
14 }
15 public void setPassword(String password) {
16 this.password = password;
17 }
18
19}
定义一个接口UserDAO
1package cn.zhang.org.dao;
2
3import cn.zhang.org.vo.User;
4
5public interface UserDAO {
6 boolean isLogin(User user);
7
8 boolean RegUser(User user);
9}
10
扩展这个接口,实现基本方法
1ackage cn.zhang.org.imp;
2
3import java.sql.Connection;
4import java.sql.PreparedStatement;
5import java.sql.ResultSet;
6import java.sql.SQLException;
7
8import cn.zhang.org.dao.UserDAO;
9import cn.zhang.org.exception.MyRuntimeException;
10import cn.zhang.org.factory.Factory;
11import cn.zhang.org.vo.User;
12
13public class UserDAOIMP implements UserDAO {
14 private static final String ISLOGINSQL = "select count(*) from t_user where username = ? and password = ?";
15 private static final String INSERTUSER = "insert into t_user(user , password) values(? , ?)";
16 public boolean isLogin(User user) {
17 boolean islogin = false;
18 ResultSet rs = null;
19 PreparedStatement pstm = null;
20 Connection conn = Factory.getMySQLCONN().getConnection();
21 try {
22 pstm = conn.prepareStatement(ISLOGINSQL);
23 pstm.setString(1, user.getUsername());
24 pstm.setString(2, user.getPassword());
25 rs = pstm.executeQuery();
26 if(rs.next()){
27 int i = rs.getInt(1);
28 if(i>0){
29 islogin = true;
30 }
31 }
32 } catch (SQLException e) {
33 throw new MyRuntimeException(e.getMessage(),e);
34 }finally{
35 close(rs, pstm, conn);
36 }
37 return islogin;
38 }
39 public void close(ResultSet rs, PreparedStatement pstm, Connection conn) {
40 try {
41 if(rs!=null){
42 rs.close();
43 }
44 } catch (SQLException e) {
45 throw new MyRuntimeException(e.getMessage(),e);
46 }
47
48 try {
49 if(pstm!=null){
50 pstm.close();
51 }
52 } catch (SQLException e) {
53 throw new MyRuntimeException(e.getMessage(),e);
54 }
55
56 try {
57 if(conn!=null){
58 conn.close();
59 }
60 } catch (SQLException e) {
61 throw new MyRuntimeException(e.getMessage(),e);
62 }
63 }
64 public boolean RegUser(User user) {
65 Connection conn = Factory.getMySQLCONN().getConnection();
66 boolean isreg = false;
67 PreparedStatement pstm = null;
68 ResultSet rs = null;
69 try {
70 pstm = conn.prepareStatement(INSERTUSER);
71 pstm.setString(1, user.getUsername());
72 pstm.setString(2, user.getPassword());
73 int i = pstm.executeUpdate();
74 if(i > 0){
75 isreg = true;
76 }
77 } catch (SQLException e) {
78 throw new MyRuntimeException(e.getMessage(),e);
79 }finally{
80 close(rs, pstm, conn);
81 }
82
83 return isreg;
84 }
85
86}