1 // ==================== Program Description ==========================
2 // 程序名称:示例13-3: UserMgr.java
3 // 程序目的:利用JDBC对数据库进行增删查改操作
4 // ==============================================================
5 import java.sql.*;
6 import test.DBConnection;
7
8 public class UserMgr
9 {
10 // 向数据库中添加用户信息
11 public boolean addUser(User user)
12 {
13 // 构造SQL语句
14 String sql = "insert into tbl_user (vcUsername, vcPassword,dtRegDate) values('" +
15 user.getUsername() + "','" + user.getPassword() +"',getDate())";
16 Statement stmt;
17 Connection conn;
18 try {
19 // 获取数据库连接
20 conn = DBConnection.getConnection();
21
22 // 创建Statement对象
23 stmt = conn.createStatement();
24
25 // 执行SQL语句
26 stmt.executeUpdate(sql);
27 stmt.close();
28 conn.close();
29
30 return true;
31 }
32 catch (SQLException e) {
33 System.out.println(e.getMessage());
34 }
35
36 return false;
37 }
38
39 // 删除数据库中某个用户的信息
40 public boolean deleteUser(User user)
41 {
42 String sql="delete from tbl_user where
vcUsername="+"'"+user.getUsername()+"'";
43 Connection conn;
44 Statement stmt;
45
46 try {
47 conn=DBConnection.getConnection();
48 stmt=conn.createStatement();
49 stmt.executeUpdate(sql);
50 stmt.close();
51 conn.close();
52
53 return true;
54 }
55 catch (SQLException e)
56 {
57 System.out.println(e.getMessage());
58 }
59
60 return false;
61 }
62
63 // 根据用户名查询数据库获取一个用户对象
64 public User getUser( String username )
65 {
66 User user;
67 String sql="select * from tbl_user where vcUsername='"+username+"'";
68 Statement stmt;
69 Connection conn;
70
71 try {
72 conn= DBConnection.getConnection();
73 stmt=conn.createStatement();
74
75 // 执行SQL语句并将查询结果放入结果集中
76 ResultSet rs=stmt.executeQuery(sql);
77
78 // 将结果集中的数据取出放入User类的对象中
79 if (rs.next())
80 {
81 user=new User();
82 user.setUsername(rs.getString("vcUsername"));
83 user.setPassword(rs.getString("vcPassword"));
84 user.setRegDate(rs.getDate("dtRegDate").toString());
85 stmt.close();
86 conn.close();
87 return user;
88 }
89 }
90 catch (SQLException e)
91 {
92 System.out.println(e.getMessage());
93 }
94
95 return null;
96 }
97
98 // 通过验证密码鉴定用户的身份
99 public int checkUser(User user)
100 {
101 User dbUser= getUser(user.getUsername());
102 if (dbUser==null)
103 return 0;
104 else if (dbUser.getPassword().equals(user.getPassword()) )
105 return 1;
106 else return -1;
107 }
108
109 // 修改数据库中某个用户的信息
110 public boolean modifyUser(User user)
111 {
112 Connection conn;
113 Statement stmt;
114 String sql="update tbl_user set vcPassword=
'"+user.getPassword()+"' where
115 vcUsername='"+user.getUsername()+"'";
116
117 try {
118 conn=DBConnection.getConnection();
119 stmt=conn.createStatement();
120 stmt.executeUpdate(sql);
121 stmt.close();
122 conn.close();
123
124 return true;
125 }
126 catch (SQLException e)
127 {
128 System.out.println(e.getMessage());
129 }
130
131 return false;
132 }
133 } |