SQL表:user_login.sql:
drop table if exists t_user;
/* ============================================================== */
/* Table: t_user */
/* ============================================================== */
create table t_user
(
id bigint auto_increment,
userName varchar ( 255 ),
userPwd varchar ( 255 ),
name varchar ( 255 ),
primary key (id)
);
insert into t_user(userName,userPwd,name) values ( ‘ zhangsan ‘ , ‘ 123 ‘ , ‘ 张三 ‘ );
insert into t_user(userName,userPwd,name) values ( ‘ llisi ‘ , ‘ 123 ‘ , ‘ 李四 ‘ );
commit ;
select * from t_user;
连接数据库测试代码:
import java.sql.* ;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test07_模拟用户登良功能的实现 {
public static void main(String[] args) {
// 初始化一个界面的方法
Map<String,String> userLogin = chuShiHuaUi();
// 验证用户名和密码
Boolean dengLu = login(userLogin);
// 最后输出结果
System.out.println(dengLu ? "登录成功!" : "登录失败!" );
}
private static Boolean login(Map<String, String> userLogin) {
// 打标记
Boolean b = false ;
Connection conn = null ;
Statement s = null ;
ResultSet rs = null ;
try {
// 1、注册驱动
Class.forName("com.mysql.jdbc.Driver" );
// 2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/donglijiedian","root","zhixi158" );
// 3、获取数据库操作对象
s = conn.createStatement();
// 4、操作MySQL // SQL语句中字符串是‘‘,要想获取数据要加双引号,中间加上数据
String sql = "select * from t_user where userName = ‘"+userLogin.get("userName")+"‘ and userPwd = ‘"+userLogin.get("userPwd")+"‘" ;
rs = s.executeQuery(sql);
// 5、处理查询结果集
// 用户名错的情况下查不到记录,用户名正确情况下也最多查出一条记录,所以用if就够了
if (rs.next()){
return true ; // 如果存在这条记录就返回
}
} catch (Exception e){
e.printStackTrace();
} finally {
// 6、释放资源,由内到外
try {
if (rs != null )
rs.close();
} catch (Exception e){
e.printStackTrace();
}
try {
if (s != null )
s.close();
} catch (Exception e){
e.printStackTrace();
}
try {
if (conn != null )
conn.close();
} catch (Exception e){
e.printStackTrace();
}
}
return b;
}
private static Map<String, String> chuShiHuaUi() {
Scanner s = new Scanner(System.in);
// 获取用户名
System.out.println("用户名:" );
String userName = s.nextLine(); // nextLine返回一行数据
// 获取密码
System.out.println("密码:" );
String userPwd = s.nextLine();
// 组装Map集合
Map<String,String> userLogin = new HashMap<> ();
userLogin.put( "userName",userName); // 添加用户名
userLogin.put("userPwd",userPwd); // 添加密码
return userLogin; // 返回集合数据
}
}
SQL注入问题:
在我们测试的时候,验证用户名和密码发现是没有问题的。
但是我们输入一些特定的字符,就发现了问题:
发现输入一些执行的字符会出现登录成功,这显然是不符合我们的需求的。
解决SQL注入的方法:
SQL注入问题
标签:sele statement incr 代码 处理 username 驱动 hashmap rgba
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did118165