其他分享
首页 > 其他分享> > Jdbc的preparement

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));
    }
}

}

标签:语句,Jdbc,String,rs,preparement,sql,con,pstmt
来源: https://www.cnblogs.com/diumyself/p/14878281.html