jdbc中PreparedStatement替换Statement实现CRUD操作

1.PreparedStatement的理解:
① PreparedStatement 是Statement的子接口
② An object that represents a precompiled SQL statement.
③ 可以解决Statement的sql注入问题,拼串问题
package loey.java1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**

  • 使用PreparedStatement完成insert、update、delete
    */
    public class JDBCTest09 {

    public static void main(String[] args) {

     Connection conn = null;
     PreparedStatement ps = null;
     try {
         Class.forName("com.mysql.jdbc.Driver");
    
         conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bjpowernode"
         ,"root","1127");
    
         //String sql = "insert into dept1(deptno,dname,loc) values(?,?,?)";插入
         //String sql = "update dept1 set dname = ? where dname = '人事部'";修改
         String sql = "delete from dept1 where dname = ?";//删除
         ps = conn.prepareStatement(sql);
    

// ps.setInt(1,50);
ps.setString(2,“人事部”);
ps.setString(3,“北京”);

        //ps.setString(1,"研发部");

        ps.setString(1,"研发部");

        int count = ps.executeUpdate();

        System.out.println((count != 0 )? "删除成功" : "删除失败");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

}

}

上一篇:SpringCloud(七)——Ribbon实现负载均衡


下一篇:【数据库基础】SQL语法基础