分析:
-
创建数据库表
-
设计
package cn.itcast.jdbc;
import util.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
* 需求:
* 1.通过键盘录入用户名和密码
* 2.判断用户是否登录成功
*/
public class login {
public static void main(String[] args) {
//键盘输入,接受用户名和密码
Scanner sc = new Scanner(System.in);
System.out.println("用户名:");
String username = sc.nextLine();
System.out.println("密码:");
String password = sc.nextLine();
//调用方法
boolean flag = new login().login(username, password);
//判断结果,输出不同语句
if(flag){
System.out.println("登陆成功!");
}else{
System.out.println("用户名或密码错误。");
}
}
/**
* 登录方法
*/
public boolean login(String username,String password){
if(username==null || password==null){
return false;
}
//连接数据库判断是否登录成功
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
/**
* select * from where username="" and password="";
* 能够查询到表示成功,不能表示失败。
*/
try {
conn = JDBCUtils.getConnection();
String sql = "select * from user where username='"+ username +"' and password='"+ password +"'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
return rs.next();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(rs,stmt,conn);
}
return false;
}
}
运行结果:
优化后:文章指路