JDBC-API详解-PreparedStatement-原理

发布时间 2023-06-15 11:33:15作者: Karlshell
        /*
         * PreparedStatement原理讲解
         * PreparedStatement的预编译功能用useServerPrepStmts=true开启
         * */
        @Test
        public void PreparedStatement2() throws Exception {
            //1.注册驱动
            //Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            String url = "jdbc:mysql:///karl?useSSL=false&useServerPrepStmts=true";
            String username = "root";
            String password = "1234";
            Connection conn = DriverManager.getConnection(url, username, password);

            //接收用户输入用户名和密码
            String name="zhangsan";
            String pwd="123";

            String Sql=" select * from tb_user where name=? and password=? ";//用英文问号

            //获取pstmt对象
            PreparedStatement pstmt = conn.prepareStatement(Sql);

            //设置?的值
            pstmt.setString(1,name);
            pstmt.setString(2,pwd);

            //执行sql
            ResultSet rs = pstmt.executeQuery();

            //判断登录是否成功
            if (rs.next()){
                System.out.println("登录成功");
            }else {
                System.out.println("登录失败");
            }

            //7.释放资源
            rs.close();
            pstmt.close();
            conn.close();
        }