PreparedStatement接口

方法   executeUpdate()         可以执行增删改语句
         executeQuery()           l可以执行查语句
好处    PrepareStatement()     提前将SQL语句发送给数据库进行编译 提高效率                                       安全性高   没有sql 注入的隐患
                                             提高了程序的可读性
PreparedStatement 步骤
1 编写sql 语句  未知内容使用? 占位符 :
             Select * from user where name=? and password=?;
              2 获得PreparedStatement对象
              3 设置实际的参数  setxxx(占位符的位置,真实的值);
              4 执行sql语句
              5 关闭资源
package cn.linjun.demo;

import JdbcUtils.JdbcDemo2;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/*
* 使用 PreparedStatement 接口完成登录
* **/
public class DemoLogin {
    public static void main(String[] args) throws SQLException {
        //从控制台输入用户密码
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入用户名");
        String name = sc.nextLine();

        System.out.println("请输入密码");
        String password = sc.nextLine();

        //登录的方法
        login(name,password);


    }
    public static void login(String name,String password) throws SQLException {
        Connection connection = JdbcDemo2.getConnection();
        //编写Sql语句  未知内容使用? 占位符
        String sql="select * from user1 where uname=? and pas=?";
        //获得PreparedStatement 对象
        PreparedStatement ps = connection.prepareStatement(sql);
        //设置实际参数  setXXX(占位符的位置,真是的值)
        ps.setString(1,name);
        ps.setString(2,password);
        //执行sql语句
        ResultSet rs = ps.executeQuery();
        if (rs.next()){
            System.out.println("登陆成功");
        }else{
            System.out.println("登录失败");
        }
        //关闭资源
        JdbcDemo2.close(rs,ps,connection);


    }
}
原文地址:https://www.cnblogs.com/qurui1998/p/10645525.html