分析:
-
创建数据库表
-
设计
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;
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;
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;
}
}
运行结果:
优化后:文章指路



