首页 » 开发 » JAVA » java常用知识:登录案例

java常用知识:登录案例

 

需求:
通过键盘录入用户名和密码
判断用户是否登录成功
select * from stu_uesr where name = "" and password="";
如果有结果则成功,没有则为失败
步骤:
1、创建数据表

1
2
3
4
5
6
7
8
create table stu_user(
    id int PRIMARY key auto_increment,
    name varchar(32),
    password varchar(32)
);

insert into stu_user values(null,"zhangsan","1234");
insert into stu_user values(null,"lisi","12345");

2.使用java判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package jdbc;

import util.JDBCUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class test03jdbc {
    public static void main(String[] args) throws SQLException {
        Scanner scan = new Scanner(System.in);
        System.out.print("请输入用户名:");
        String name = scan.nextLine();
        System.out.println("");
        System.out.print("请输入密码:");
        String password = scan.nextLine();
        boolean flag = new test03jdbc().login(name, password);
        if(flag){
            System.out.println("登录成功!");
        }else{
            System.out.println("登录失败!");
        }
    }

    public boolean login(String name,String password) {
        if(name ==null || password ==null){
            return false;
        }
        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from stu_user where name = '"+name+"'and password='"+password+ "'";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.close(rs,stmt,conn);
        }
        return false;
    }
}

原文链接:java常用知识:登录案例,转载请注明来源!

0