package com.itheima.test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class Test1 {
public void Logintest() throws IOException{
//MyBaits获取数据库数据的固定代码
//获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session回话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
System.out.println("用户名:");
Scanner username = new Scanner(System.in);
String read1 = username.nextLine();
//System.out.println("输入用户名:" + read1);
System.out.println("密码:");
Scanner password = new Scanner(System.in);
String read2 = password.nextLine();
//System.out.println("输入密码:" + read2);
String password1 = sqlSession.selectOne("userMapper.findPWDByName",read1);
if (read2.equals(password1)){
System.out.println("登录成功");
}else {
System.out.println("用户名密码错误");
}
sqlSession.close();
}
public static class Tests {
public static void main(String[] args) throws IOException {
Test1 test1 = new Test1();
test1.Logintest();
}
}
}
先在文件中写入关于具体操作的代码:
1. 首先使用MyBaits配置从数据库中获取数据
2. 用户先输入用户名username,然后输入密码password
根据username使用sql语句findPWDByName方法从数据库中查询对应的密码,
如果符合,则登录成功
否则,显示用户名密码错误。
第二种方法:
我在测试文件中直接写了登录功能的测试方法,一开始遇到了无法在控制台输入数据的情况(已解决),但是在结果的显示中,我自己输入的数据(即username,password)在最后结果出现时,这些数据是看不到的。
@Test
//查询操作
public void test7() throws IOException {
//获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session回话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
System.out.println("用户名:");
Scanner username = new Scanner(System.in);
String read1 = username.nextLine();
//System.out.println("输入用户名:" + read1);
System.out.println("密码:");
Scanner password = new Scanner(System.in);
String read2 = password.nextLine();
//System.out.println("输入密码:" + read2);
String password1 = sqlSession.selectOne("userMapper.findPWDByName",read1);
if (read2.equals(password1)){
System.out.println("登录成功");
}else {
System.out.println("用户名密码错误");
}
sqlSession.close();
}
附:关于在控制台键盘输入数据的解决办法
在Help中的Edit Custom VM Options中加入



