-
- 案例:
-
代码实现:
package JDbc;
import java.sql.*;
import java.util.Scanner;
public class jdbcdome_PreparedStatement {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://127.0.0.1:3306/homework?useSSL=false";
String user="root";
String password="1234";
Connection connection = DriverManager.getConnection(url, user, password);
Scanner scanner=new Scanner(System.in);
System.out.println("亲输入账号");
int name = Integer.parseInt(scanner.nextLine());
System.out.println("亲输入密码");
String paw = scanner.nextLine();
String sql ="select *from lyj where id='"+name+"'and sid='"+paw+"'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()){
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
resultSet.close();
statement.close();
connection.close();
}
} -
sql注入
-
navicat中的sql注入:
-
解决sql注入:通过字符串拼接时候的转译(/)实现
-
代码实现:
package JDbc;
import java.sql.*;
import java.util.Scanner;
public class PreparedStatement {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql:///homework?useSSL=false";
String user="root";
String password="1234";
Connection connection = DriverManager.getConnection(url, user, password);
Scanner scanner=new Scanner(System.in);
System.out.println("亲输入账号");
int name = Integer.parseInt(scanner.nextLine());
System.out.println("亲输入密码");
String paw = scanner.nextLine();
String sql ="select *from lyj where id=? and sid=?";
java.sql.PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,name);
preparedStatement.setString(2,paw);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
System.out.println("执行成功");
}else {
System.out.println("执行失败");
}
}
}