public class MyTest1 { public static void main(String[] args) { Connection connection = null; PreparedStatement pps = null; ResultSet resultSet = null; try { //1.加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2.获得连接 String username = "root"; String Pwd = "123456"; String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC"; connection = DriverManager.getConnection(url,username,Pwd); //3 定义sql 创建预状态通道 String sql = "select * from users where userid = ? and password = ?"; pps = connection.prepareStatement(sql); String userid = "123"; String password = "345112"; //给占位符赋值 pps.setString(1,userid); pps.setString(2,password); //执行sql resultSet = pps.executeQuery(); //4 取出结果集 if (resultSet.next()){//判断是否有下一条数据 System.out.println("登录成功!"); }else{ System.out.println("登录失败!"); } } catch (SQLException | ClassNotFoundException throwables) { throwables.printStackTrace(); }finally { try { if(resultSet != null){ resultSet.close(); } if (pps != null){ pps.close(); } if(connection != null){ connection.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
JAVA-JDBC之预状态通道防止SQL注入
最新推荐文章于 2023-02-12 22:52:34 发布