Jdbc的preparement

import java.sql.*;

public class JdbcDemo2 {
public static void main(String[] args) throws SQLException {
//创建连接
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "1234");
//增
//sql语句
String sql="insert into jdbcdemo values(null,?,?)";
//创建操作sql语句对象,
PreparedStatement pstmt = con.prepareStatement(sql);//将sql语句进行预加载
//对占位符进行传参
pstmt.setString(1,"eee"); //setXXX,?中参数是什么类型,XXX就写成什么类型
pstmt.setString(2,"1221");
//执行sql语句
int i = pstmt.executeUpdate();
System.out.println(i);

    //删
    String sql="delete from jdbcdemo where id=?";
    //获取操作语句对象
    PreparedStatement pstmt = con.prepareStatement(sql);
    //对占位符进行传参
    pstmt.setInt(1,6);
    //执行sql
    int i = pstmt.executeUpdate();
    System.out.println(i);

    //改
    //sql语句
    String sql="update jdbcdemo set username=?,password=? where id=?";
            //获取执行操作sql语句对象
    PreparedStatement pstmt = con.prepareStatement(sql);
    //对占位符进行传参
    pstmt.setString(1,"改名");
    pstmt.setString(2,"改密码");
    pstmt.setInt(3,5);
    int i = pstmt.executeUpdate();
    System.out.println(i);

    //查
    //sql语句
   String sql="select * from jdbcdemo where id>?";
   //获取语句对象并且预编译
    PreparedStatement pstmt = con.prepareStatement(sql);
    //对占位符进行传递参数
    pstmt.setInt(1,1);
    //执行sql
    ResultSet rs = pstmt.executeQuery();
    //处理结果集
    while (rs.next()){
        System.out.println( rs.getString(1)+"---"+rs.getString(2)+"---"+rs.getString(3));
    }
}

}

posted @ 2021-06-12 14:57  一只带不动的小菜鸡  阅读(107)  评论(0编辑  收藏  举报