package mysql_jdbc;
import utils.MySQLtool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
import java.util.UUID;
/*
使用JDBC模拟登录注册案例1.0----解决sql注入问题
因为写sql语句时,是将值传进去之后再进行编译的,
如果传入的是 1234wewx' or '1'='1,sql就会把or当成语言进行编译,
那么无论密码是什么都能登录
所以需要预编译
*/
public class JDBCtest8 {
public static void main(String[] args) throws Exception {
System.out.println("欢迎进入车辆管理系统!");
System.out.println("北京第三区交通委提醒您:\n道路千万条,安全第一条。\n行车不规范,亲人两行泪。");
System.out.println("请输入用户名:");
Scanner sc = new Scanner(System.in);
String trusername = sc.nextLine();
System.out.println("请输入密码:");
String trpassword = sc.nextLine();
Connection conn = MySQLtool.init();
//编写sql语句 在数据库中进行查询,?代表占位符
String s = "select trusername,trpassword from tcs where trusername=?and trpassword=?";
//进行预编译
PreparedStatement pps = conn.prepareStatement(s);
//给占位符?进行传值
pps.setString(1,trusername);
pps.setString(2,trpassword);
//如果查询到就给相关提示,查不到就提示创建(向数据库添加)
ResultSet resultSet = pps.executeQuery();
boolean b = resultSet.next();
//b为true,表示数据库中有数据,即之前注册过了,就返回登陆成功。
if (b) {
System.out.println("登陆成功");
//b为false,表示数据库中没有数据,需要重新注册。
} else {
System.out.println("您还未注册,是否立即注册?(是/否)");
String choice = sc.nextLine();
while(true){
if ("是".equals(choice)) {
System.out.println("注册用户名:");
String new_trusername = sc.nextLine();
System.out.println("设置密码:");
String new_trpassword = sc.nextLine();
System.out.println("再次输入密码:");
String new_trpassword_again = sc.nextLine();
//如果两次密码一致,开始注册。否则提示:两次密码不一致
if (new_trpassword_again.equals(new_trpassword)){
UUID uuid = UUID.randomUUID();
long l = System.currentTimeMillis();
String id = uuid + "-" + l;
int count = pps.executeUpdate("insert into tcs(id,trusername,trpassword) values('" + id + "','" + new_trusername + "','" + new_trpassword + "')");
System.out.println(count == 1 ? "注册成功" : "注册失败");
break;
} else{
System.out.println("两次密码不一致,请重新输入!");
}
}
else if ("否".equals(choice)) {
System.out.println("您取消了注册,正在退出");
System.exit(0);
} else {
System.out.println("输入错误!");
break;
}
}
//释放资源
pps.close();
conn.close();
}
}
}
9、JDBC编程---案例1.0解决sql注入问题
最新推荐文章于 2024-05-22 20:11:58 发布