1、创建一个模拟的类UserLogin
package com.sie.train;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class UserLogin {
public static void main(String[] args) {
//(1)从控制台输入用户名与密码
Scanner scanner=new Scanner(System.in);
System.out.print("请输入用户名:");
String uname=scanner.nextLine();
System.out.print("请输入密码:");
String pwd=scanner.nextLine();
//(2)连接数据库,先判断用户名存不存在再判断用户密码有没有输入正确
String url="jdbc:oracle:thin:@61.145.96.125:1522:DEMO";
String user="apps";
String password="apps";
//用Statement的安全性低,容易被SQL注入攻击例如:用户名:admin 密码:1' OR '1'='1,就可以成功登陆
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection(url,user,password);
String sql="SELECT * FROM T_User WHERE uname='"+uname+"' AND passwd ='"+pwd+"'";
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
System.out.println(sql);
if (rs.next()){
System.out.println("登陆成功!");
}else{
System.out.println("登陆失败!");
}
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2、结果如下:
3、Statemant另外一种防止SQL注入的写法:
package com.sie.train;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class UserLogin{
// @UserLogin1 Statement防SQL注入的写法
public static void main(String[] args) {
// (1)从控制台输入用户名与密码
Scanner scanner = new Scanner(System.in);
System.out.print("请输入用户名:");
String uname = scanner.nextLine();
System.out.print("请输入密码:");
String pwd = scanner.nextLine();
// (2)连接数据库,先判断用户名存不存在,再判断用户密码有没有输入正确
String url = "jdbc:oracle:thin:@61.145.96.125:1522:DEMO";
String user = "apps";
String password = "apps";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, user, password);
String sqlUname = "SELECT uname FROM T_User WHERE uname='" + uname
+ "' ";
Statement stmt = conn.createStatement();
ResultSet rsUname = stmt.executeQuery(sqlUname);
if (rsUname.next()) {
String sqlPwd = "SELECT passwd FROM t_user WHERE uname='"
+ uname + "'";
ResultSet rsPwd = stmt.executeQuery(sqlPwd);
if (rsPwd.next()) {
String uppwd = rsPwd.getString("passwd");
if (uppwd.equals(pwd)) {
System.out.println("登陆成功!");
} else {
System.out.println("登陆失败!");
}
}
rsPwd.close();
} else {
System.out.println("用户名不存在!");
}
rsUname.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}