import java.sql.*;
public class Demo1 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获得链接
String userName = "root";
String password = "root";
String url = "jdbc:mysql://localhost:3306/yhp2?serverTimezone=UTC";
connection = DriverManager.getConnection(url,userName,password);
//3.定义sql,创建状态通道(进行sql语句的发送)
statement = connection.createStatement();
变量范围
String uname = "abcd"; //在表记录中,abcd为错误uname,aa为正确 uname 错误但能执行成功
// " '' or 1=1" 定义的变量值,即为输入的值
// 方法不安全
// 1=1表示恒成立条件 or表示其中一个满足都满足
String pass = " '' or 1=1"; //在表记录中,111为正确pass
resultSet = statement.executeQuery("select * from users2 where username='"+uname+"' and password="+pass); //executeQuery(sql)执行增删改时使用
if(resultSet.next()){
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
//5.关闭资源
if(resultSet !=null){
resultSet.close();
}
if(statement !=null){
statement.close();
}
if( connection !=null){
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}

本文展示了一个使用Java进行数据库操作的例子,并通过一个简单的登录验证过程揭示了SQL注入的风险。文章详细介绍了如何加载数据库驱动、建立连接、执行SQL查询及处理结果集。
941

被折叠的 条评论
为什么被折叠?



