package cn.bruce.MySql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Scanner; public class LOGON { public static void main(String[] args) { String usename, password, url, sql, jdbc, sname, spass; Connection con = null; usename = "root"; password = "jinqi1986"; url = "jdbc:mysql://localhost:3306/mytrain?useSSL=false&serverTimezone=CTT"; // url = // "jdbc:mysql://localhost:3306/mytrain?useSSL=false&serverTimezone=CTT"; sql = "select * from users "; jdbc = "com.mysql.cj.jdbc.Driver"; // 加载驱动 try { Class.forName(jdbc); System.out.println("加载驱动成功!"); } catch (Exception e) { System.out.println("加载驱动失败!"); } // 连接数据库 try { con = DriverManager.getConnection(url, usename, password); System.out.println("连接数据库成功!"); } catch (Exception e) { System.out.println("连接数据库失败!"); } // 执行SQL语句-注入攻击实例 try { Statement sa = con.createStatement(); Scanner sc = new Scanner(System.in); // 用户名和密码可以随便输 System.out.println("请输入用户名:"); String n = sc.nextLine(); // 只要密码输入里有'or' 1=1就可以进行SQL漏洞攻击 System.out.println("请输入密码:"); String p = sc.nextLine(); sql = "select * from users where zusename = '" + n + "' and zpassword = '" + p + "';"; System.out.println(sql); ResultSet rs = sa.executeQuery(sql); while (rs.next()) { System.out.println("用户名:" + rs.getString("zusename") + " " + "密码:" + rs.getString("zpassword")); } } catch (Exception e) { e.printStackTrace(); } // 执行SQL语句-使用预编译实例--推荐使用这种使用方法 try { Scanner sc = new Scanner(System.in); System.out.println("请输入用户名:"); String n = sc.nextLine(); System.out.println("请输入密码:"); String p = sc.nextLine(); // sql语句中的参数全部采用?进行占位 sql = "select * from users where zusename = ? and zpassword = ?"; PreparedStatement ps = con.prepareStatement(sql);// 预编译 // 使用ps的set方法进行参数的赋值 ps.setString(1, n); ps.setString(2, p); System.out.println(sql); ResultSet rs = ps.executeQuery();// 参数不需要SQL while (rs.next()) { System.out.println("用户名:" + rs.getString("zusename") + " " + "密码:" + rs.getString("zpassword")); } rs.close();// 关rs } catch (Exception e) { e.printStackTrace(); } finally { try { con.close();// 关连接 } catch (Exception e2) { e2.printStackTrace(); } } } }