目录
1.开始之前你需要先做一些准备工作:
1.确保已经安装mysql和mysql-connector文件,配置环境变量(我的是直接把mysql的bin文件的安装路径D:\MySQL\mysql-8.0.29\bin;放到环境变量path里面了),第2个文件夹是jdbc连接数据库用的
2.把用户表t_user导入到数据库中
drop table if exists t_user;
create table t_user
(
id bigint auto_increment,
loginName varchar(255),
loginPwd varchar(255),
realName varchar(255),
primary key (id)
);
insert into t_user(loginName,loginPwd,realName) values('zhangsan','123','张三');
insert into t_user(loginName,loginPwd,realName) values('jack','123','杰克');
commit;
select * from t_user;
2.打开idea
1.创建java项目
2.导入mysql-connector文件的jar包
src下面建一个包jdbc
包下面建一个类jdbcTest
把下面代码粘贴进去
package jdbc;
import java.sql.*;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Map;
public class jdbcTest {
public static void main(String[] args) {
//调用initUI()方法获取用户输入的用户名和密码
Map<String,String> userLoginInfo=initUI();
//调用login()方法
boolean loginSuccess=login(userLoginInfo);
System.out.println(loginSuccess?"登陆成功":"登录失败");
}
//该方法把用户输入的信息与数据库中的比对,如果符合返回true,否则返回false
private static boolean login(Map<String,String> userLoginInfo) {
boolean loginSuccess=false;
//用两个变量获取用户输入的用户名和密码
String loginName=userLoginInfo.get("loginName");
String loginPwd=userLoginInfo.get("loginPwd");
//定义3个变量
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cnm", "root", "123456");
//3.获取数据库操作对象(执行sql语句的对象)
stmt = conn.createStatement();
//4.执行sql语句
String sql = "select * from t_user where loginName='" + loginName + "' and loginPwd='" + loginPwd + "'";
rs = stmt.executeQuery(sql);
//5.处理结果(如果结果集有数据则 rs. next()返回true,否则返回false)
if (rs. next()) {
loginSuccess = true;
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
//6.释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return loginSuccess;
}
/*
*该方法获取控制台输入的用户名和密码
* */
private static Map<String, String> initUI () {
Scanner s = new Scanner(System.in);
System.out.println("用户名:");
String loginName = s.nextLine();
System.out.println("密码:");
String loginPwd = s.nextLine();
Map<String, String> userLoginInfo = new HashMap<>();
userLoginInfo.put("loginName", loginName);
userLoginInfo.put("loginPwd", loginPwd);
return userLoginInfo;
}
}
运行