package com.cqust;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
- 解决sql注入问题使用预编译
- 在还没有拼接sql的时候,直接编译
-
需要传值的位置使用?
-
使用PreparedStatement 效率比较高,sql一次编译可以执行n次,Statement是编译一次执行一次
- 多数时候使用PreparedStatement,如果要求使用sql注入,或者字符串拼接则使用Statement
- PreparedStatement statement = connection.prepareStatement(sql);
*
statement.setString(1,username);传值这里传值会做类型检查比较安全
*
statement.setString(2,userpwd);传值
*
1,2分别指的是第一个,第二个?
- statement.executeQuery();这里执行的时候不需要传sql了
*/
public class JDBCTest06 {
public static void main(String[] args) throws Exception {
//初始化界面,返回用户输入的信息,使用map集合存储
Map
}
/**
* 用户登录界面
* @return 返回用户的信息,存在集合中
*/
public static Map<string,string> initLogin(){
Map<string,string> userInfo = new HashMap<>();
System.out.print("请输入你的用户名:");
Scanner scanner = new Scanner(System.in);
String username = scanner.next();
System.out.print("请输入你的密码:");
String userpwd = scanner.next();
userInfo.put("username",username);
userInfo.put("userpwd",userpwd);
return userInfo;
}
/**
* 使用jdbc技术完成登录检测
* @param map 用户的信息存储在集合map中
* @return 最后返回登录成功还是失败
* @throws Exception 这里为了省点劲直接throws
*/
public static boolean login(Map<string,string> map) throws Exception{
String username = map.get("username");
String userpwd = map.get("userpwd");
boolean loginInfo = false;
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cqust_db",
"root","hch1");
//3.获取数据库操作对象,预编译sql
String sql = "select username,userpwd from t_user_login where username = ? and userpwd = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,username);
statement.setString(2,userpwd);
//4.执行sql
//String sql = "select username,userpwd from t_user_login where username = '"+username+"' and userpwd = '"+userpwd+"'";
ResultSet resultSet = statement.executeQuery();
//5.这里只需要看是否有数据,如果查询到数据,则登录成功,直接loginInfo = true;
if (resultSet.next()){
loginInfo = true;
}
//6.关闭资源
if (resultSet!=null){
resultSet.close();
}
if (statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
return loginInfo;
}
</string,string></string,string></string,string>
}
Original: https://www.cnblogs.com/journeyhch/p/15574236.html
Author: journeyhch
Title: jdbc-实现用户登录业务(解决sql注入问题)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/508022/
转载文章受原作者版权保护。转载请注明原作者出处!