使用PreparedStatement代替Statement

import java.sql.*;

import java.sql.Connection;
import java.sql.DriverManager;

public class PrepareStToSolveInject{
    
    
    public static void main(String[] args) throws ClassNotFoundException,SQLException{
    
    
        String url = "jdbc:mysql://localhost:3306/schoola?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
        String username = "root";//登录账户
        String password = "root";//登录密码

        Connection connection = DriverManager.getConnection(url,username,password);

        //--------------------------------插入记录-----------------------------------------

        String sql = "insert into `student`(`id`,`name`,`sex`,`age`) values(?,?,?,?)";//用问号代替具体值,值稍后再设置

        PreparedStatement pSt = connection.prepareStatement(sql);//这里sql传入并没有执行,要执行则调用execute()方法,PreparedStatement与Statement的区别在于,PSt预编译sql语句,先写,然后不执行

        pSt.setInt(1,19);//给参数赋值,1代表第一个?的位置,13代表这个问号位置的值
        pSt.setObject(2,"建国");//不知道要赋值的列的属性时可用setObject代替,知道时就用对应的类型
        pSt.setString(3,"男");
        pSt.setInt(4,24);

        int i = pSt.executeUpdate();//这里就不需要传参了,因为参数在建立pSt对象的时候就传好了。执行这个方法会返回受影响的行数,赋值给i来判断插入是否成功
        if(i > 0){
    
    
            System.out.println("插入成功");
        }
        /*上面如果用Statement实现:

        Statement st = connection.createStatement();
        String sql = "insert into `student`(`id`,`name`,`sex`,`age`) values(19,"建国","建国",24)";
        int i = st.execute(sql);
        if(i > 0){
            System.out.println("插入成功");
        }

        */

        //--------------------------------修改记录-----------------------------------------
        String sql1 = "update `studet` set `age` = ? where id =?";
        PreparedStatement pSt1 = connection.prepareStatement(sql1);
        pSt1.setInt(1,22);
        pSt1.setInt(2,12);
        int j = pSt.executeUpdate();
        if(j>0){
    
    
            System.out.println("修改成功");
        }

        pSt.close();
        pSt1.close();
        connection.close();
    }
}

猜你喜欢

转载自blog.csdn.net/kitahiragawa/article/details/111823198