一、代码
package d03_system;
import java.sql.*;
import java.util.Scanner;
/**
* zt
* 2020/8/20
* 14:19
* 1.注册驱动(可省略)
* 2.创建链接
* 3.创建命令
* 4.执行命令
* 5.关闭资源
*
* PreparedStatement pstat = conn.prepareStatement("select * from user where name=? and password=?");避免sql注入,出现(大明' or 1=1;#)错误
*/
public class Login {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("------------------欢迎登录-------------------");
System.out.println("请输入你的用户名 (づ ̄3 ̄)づ╭❤~");
String username = sc.nextLine();
System.out.println("请输入你的密码 ︿( ̄︶ ̄)︿");
String password = sc.nextLine();
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建链接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gp2002?useSSL=false&characterEncoding=utf8", "root", "root");
//3.创建命令
// Statement stat = conn.createStatement();
//3.1?占位符,执行时会替换为实际数据(自动转译不会出现sql注入)
PreparedStatement pstat = conn.prepareStatement("select * from user where name=? and password=?");
//3.2给占位符赋值
pstat.setString(1, username);
pstat.setString(2, password);
ResultSet rs = pstat.executeQuery();
//4.执行命令
// ResultSet rs = stat.executeQuery("select * from user where name='" + username + "' and password ='" + password + "';");
//5.遍历
if(rs.next()){
System.out.println("登陆成功ヽ(✿゚▽゚)ノ");
}else{
System.out.println("登陆失败Σ( ° △ °|||)︴");
}
/*ResultSet rs = stat.executeQuery("select name,password from user;");
while(rs.next()) {
String name1 = rs.getString("name");
String password1 = rs.getString("password");
if (name1.equals(username) && password1.equals(password)) {
System.out.println("登陆成功ヽ(✿゚▽゚)ノ");
break;
// return;
} else {
System.out.println("登陆失败Σ( ° △ °|||)︴");
}
}*/
//6.关闭
rs.close();
pstat.close();
conn.close();
}
}
二、运行结果
------------------欢迎登录-------------------
请输入你的用户名 (づ ̄3 ̄)づ╭❤~
saf' or 1=1;#
请输入你的密码 ︿( ̄︶ ̄)︿
4564
登陆失败Σ( ° △ °|||)︴
Process finished with exit code 0