JDBC判断是否是新用户

 1 import java.sql.Connection;
 2 import java.sql.PreparedStatement;
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 
 6 /*
 7 * 判定插入的用户数据是否已经存在
 8 *   1、如果存在,返回失败信息
 9 *   2、如果不存在,返回插入成功信息
10 * */
11 public class UserDao6 {
12     Connection connection = null;
13     PreparedStatement preparedStatement = null;
14     ResultSet resultSet = null;
15     JDBC jdbc = new JDBC();
16 
17     public boolean pd(User user){
18         try {
19             //1 2
20             connection = jdbc.connect();
21 
22             //a 查询用户是否已经存在数据库之中
23             String sql = "select * from t_user where user_name=? and passwd=?";
24             preparedStatement = connection.prepareStatement(sql);
25 
26             //b 填充问号
27             preparedStatement.setString(1,user.getUserName());
28             preparedStatement.setString(2,user.getPassword());
29 
30             //c 执行sql语句
31            resultSet = preparedStatement.executeQuery(); 
32 
33            //d
34 //            System.out.println(resultSet.next()); //resultSet.next() 当前行有效,返回true,否则返回false
35             if (resultSet.next() == false) 
36             {
37                 return false;
38             }
39         } catch (SQLException throwables) {
40             throwables.printStackTrace();
41         }finally {
42 
43             if (resultSet != null)
44             {
45                 try {
46                     resultSet.close();
47                 } catch (SQLException throwables) {
48                     throwables.printStackTrace();
49                 }
50             }
51 
52             if (preparedStatement != null)
53             {
54                 try {
55                     preparedStatement.close();
56                 } catch (SQLException throwables) {
57                     throwables.printStackTrace();
58                 }
59             }
60             if (connection != null)
61             {
62                 try {
63                     connection.close();
64                 } catch (SQLException throwables) {
65                     throwables.printStackTrace();
66                 }
67             }
68         }
69         return true;
70     }
71 }

resultSet.next(); //如果新的当前行有效,则返回 true;如果不存在下一行,则返回 false
posted @ 2021-02-24 13:35  陌上尘如玉  阅读(196)  评论(0)    收藏  举报