1.1 效果图演示:java
1.2 数据准备:mysql
CREATE TABLE USER (
id INT AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(50),
PASSWORD VARCHAR(50)
);
INSERT INTO USER (NAME, PASSWORD) VALUES('admin', '123'), ('test', '123'), ('gm', '123');
1.3 代码实现:sql
工具类
package Utils;
import java.sql.*;
import java.util.Collection;
/*
工具类
*/
public class JDBCUtils {
public static final String DIVERCLASS = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/test";
public static final String USER = "root";
public static final String PASSWORD = "root";
//每次别人获取链接的时候,都须要加载该类。可是一个类只须要加载一次就够了。静态代码块只须要执行一次。
static {
try {
Class.forName(DIVERCLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//链接
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL,USER,PASSWORD);
return connection;
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//关闭资源
public static void close(ResultSet rs, Statement st,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package com.enjoy.test;
import Utils.JDBCUtils;
import java.sql.*;
import java.util.Scanner;
public class LoginTest {
public static void main(String[] args)throws Exception {
//建立扫描器
Scanner sc = new Scanner(System.in);
System.out.println("请输入帐号:");
String userName = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
boolean flag = login(userName,password);
if(flag){
System.out.println("恭喜"+userName+"登陆成功");
}else {
System.out.println("帐号或密码错误或不存在");
}
}
private static boolean login(String userName, String password) throws Exception {
//获取对象
Connection connection = JDBCUtils.getConnection();
//获取SQL运输器
String sql = "select*from user where name=? and password=?";
//获得预编译对象
PreparedStatement pst = collection.prepareStatement(sql);
//给?赋值
pst.setString(1,userName);
pst.setString(2,password);
//执行SQL
ResultSet rs = pst.executeQuery();
return rs.next();
}
}