主方法
具有SQL注入攻击
由于sql语句参数部分是由前台发往后台,后台的sql语句是拼接而来,如果拼接的过程中出现数据库的关键字就有可能拼接出的sql语句的语义发生改变从而执行一些其他操作—sql注入攻击 #号表示注释
避免SQL注入攻击
完整代码
package cn.tedu.jdbc.sql;
import cn.tedu.jdbc.utiles.JDBCUtils;
import java.sql.*;
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入用户名:");
String name = sc.nextLine();
System.out.println("请输入密码:");
String password=sc.nextLine();
textLogin(name,password);
}
private static void textPreparedLogin(String name, String password) {
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement("select * from user where name=? and password=?");
ps.setString(1,name);
ps.setString(2,password);
rs = ps.executeQuery();
if(rs.next()){
System.out.println("登录成功!!");
}else {
System.out.println("登录失败!!!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(conn,ps,rs);
}
}
private static void textLogin(String name, String password) {
Connection conn=null;
Statement stat=null;
ResultSet rs=null;
try {
conn = JDBCUtils.getConnection();
stat = conn.createStatement();
rs = stat.executeQuery("select * from user where name='" + name + "' and password='" + password + "'");
if(rs.next()){
System.out.println("登录成功!!!");
}else {
System.out.println("登录失败!!!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(conn,stat,rs);
}
}
}
|