1 package com.yxfyg.dao;
2
3 public interface UserDao{
4
5 void findAll();
6
7 void insert(String username,String password,String phone);
8
9 void update(int uid,String phone);
10
11 void delete(int uid);
12 }
1 package com.yxfyg.dao.impl;
2
3 import java.sql.Connection;
4 import java.sql.PreparedStatement;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Statement;
8
9 import com.yxfyg.dao.UserDao;
10 import com.yxfyg.util.JDBCUtil;
11
12 public class UserDaoImpl implements UserDao{
13
14 @Override
15 public void findAll() {
16 Connection conn = null;
17 Statement st = null;
18 ResultSet rs = null;
19 try {
20 conn = JDBCUtil.getConn();
21 st = conn.createStatement();
22 String sql = "select * from user";
23 rs = st.executeQuery(sql);
24 while(rs.next()) {
25 int uid = rs.getInt("uid");
26 String username = rs.getString("username");
27 String password = rs.getString("password");
28 String phone = rs.getString("phone");
29 System.out.println("uid="+ uid +",username="+ username +",password="+ password +",phone="+ phone);
30 }
31 } catch (SQLException e) {
32 e.printStackTrace();
33 }finally {
34 JDBCUtil.release(rs, st, conn);
35 }
36 }
37
38 @Override
39 public void insert(String username, String password, String phone) {
40 Connection conn = null;
41 PreparedStatement ps = null;
42 try {
43 conn = JDBCUtil.getConn();
44 String sql = "insert into user values(null,?,?,?)";
45 ps = conn.prepareStatement(sql);
46 ps.setString(1, username);
47 ps.setString(2, password);
48 ps.setString(3, phone);
49 int row = ps.executeUpdate();
50 if(row > 0) {
51 System.out.println("插入成功");
52 }else {
53 System.out.println("插入失败");
54 }
55 } catch (SQLException e) {
56 e.printStackTrace();
57 }finally {
58 JDBCUtil.release(ps,conn);
59 }
60 }
61
62 @Override
63 public void update(int uid, String phone) {
64 Connection conn = null;
65 PreparedStatement ps = null;
66 try {
67 conn = JDBCUtil.getConn();
68 String sql = "update user set phone = ? where uid = ?";
69 ps = conn.prepareStatement(sql);
70 ps.setString(1, phone);
71 ps.setInt(2, uid);
72 int row = ps.executeUpdate();
73 if(row > 0) {
74 System.out.println("修改成功");
75 }else {
76 System.out.println("修改失败");
77 }
78 } catch (SQLException e) {
79 e.printStackTrace();
80 }finally {
81 JDBCUtil.release(ps,conn);
82 }
83 }
84
85 @Override
86 public void delete(int uid) {
87 Connection conn = null;
88 PreparedStatement ps = null;
89 try {
90 conn = JDBCUtil.getConn();
91 String sql = "delete from user where uid = ?";
92 ps = conn.prepareStatement(sql);
93 ps.setInt(1, uid);
94 int row = ps.executeUpdate();
95 if(row > 0) {
96 System.out.println("删除成功");
97 }else {
98 System.out.println("删除失败");
99 }
100 } catch (SQLException e) {
101 e.printStackTrace();
102 }finally {
103 JDBCUtil.release(ps,conn);
104 }
105 }
106 }