PreparedStatement对象来实现JDBC增删改查

一. PreparedStatement与Statement的区别

1.不需要sql语句拼接,防止sql注入,更加安全

2.用占位符的方式写sql,便于后期维护,提高代码可读性,可以自动对类型进行转换

3.有预编译功能,可以大批量处理sql,(mysql不明显,Oracle很明显)

4.向数据库中添加一条数据

5.PreparedStatement:用于执行sql语句的对象

6.用connection的PreparedStatement(sql)方法获取

7.用executeUpdate(sql)执行sql语句

* 注意:只能执行 insert,update,delect,不能执行select

 

二.这是连接数据库的方法,放到此工具类中

package com.zhiyou.jdbc.connection;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCTools {
  
 /**
     * 这是连接数据库的方法,放到此工具类中
     * @return
     * @throws IOException 
     *
     *
     */

    static Connection con;
    static String url;
    static Properties properties;
    static{
 
       //1.创建properties对象
        properties = new Properties();
        try {
      
     //2.从类路径下加载db.properties文件
            properties.load(JDBCTools.class.getClassLoader().getResourceAsStream("db.properties"));
        
    //3.获取db.properties中加载的url信息
            url=properties.getProperty("url");
        } catch (IOException e) {
            e.printStackTrace();
        }
          
    }

    //4.通过DriverManager的getConnection()方法获取数据库连接

    public static Connection getConnections(){
        try {
            con = DriverManager.getConnection(url,properties);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
     
    }

    /**
      *这是关闭数据库的工具方法,因为曾删改都需要用,所以写在此工具方法中
    */

    public static void close(Statement statement,Connection con){
        try {
            statement.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            con.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }

}

1、增加

public void testPreparedStatement(){
      Connection con=null;
      PreparedStatement pstmt=null;//创建PreparedStatement对象
      try {
     
     //1、准备Connection连接数据库
            con=JDBCTools.getConnections();
   
      //2、准备sql语句
          //sql语句不再采用拼接方式,应用占位符问号的方式写sql语句。

          String sql="insert into users(name,age,email) values(?,?,?)";
          pstmt =con.prepareStatement(sql);
     
    //4、占位符设置值
          pstmt.setString(1, "zdm");
          pstmt.setInt(2, 27);
          pstmt.setString(3, "1583785269@qq.com");
   
      //5、执行sql
          pstmt.executeUpdate();
     } catch (SQLException e) {
        e.printStackTrace();
     }finally{

         //6、关闭数据库等
         JDBCTools.close(pstmt, con); 
     }
    }

2、修改 

 public void testPreparedStatement(){
          Connection con=null;
          PreparedStatement pstmt=null;
//创建PreparedStatement对象
            try {
                con=JDBCTools.getConnection();
            
   //sql语句不再采用拼接方式,应用占位符问号的方式写sql语句。
                String sql="update users set name=?,age=?,email=? where id=?";
        
       //对占位符设置值,占位符顺序从1开始,第一个参数是占位符的位置,第二个参数是占位符的值。
               pstmt=con.prepareStatement(sql);
               pstmt.setString(1, "asas");
                pstmt.setInt(2, 12);
                pstmt.setString(3, "asa@jjj");
                pstmt.setInt(4, 11);
      
         //执行sql
                preStatement.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{

             //关闭数据库等
              JDBCTools.close(pstmt, con);
            }
        }

 

4、查询

public void PreparedStatement(){
        Connection con=null;
        PreparedStatement pstmt=null;
//创建PreparedStatement对象
        ResultSet res=null;
      try {
     
    //1.准备Connection连接数据库
          

          con=JDBCTools.getConnections();            
          //2.准备sql字符串
          
          String sql="select * from users where id=8";
     
    //3.准备prepareStatement
          

          pstmt=con.prepareStatement(sql);
          
 
        //4.执行sql得到ResultSet
          

          res = pstmt.executeQuery();
          
   
      //5.处理ResultSet显示查询到的结果
          

          while(res.next()){
              int id=res.getInt(1);
              String name=res.getString(2);
              int age=res.getInt(6);
              String email=res.getString(4);
              System.out.println("id"+id+"\t name"+name+"\t email"+email);
          }
          
      } catch (Exception e) {
          e.printStackTrace();
      }finally{
   
    //6.关闭
          JDBCTools.close(res, pstmt, con);
      }
    }

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用 PreparedStatement 编写通讯录代码,实现增删功能的示例代码: ```java import java.sql.*; public class AddressBook { private static final String url = "jdbc:mysql://localhost:3306/addressbook"; private static final String username = "root"; private static final String password = "123456"; public static void main(String[] args) { try { Connection conn = DriverManager.getConnection(url, username, password); // 创建通讯录表 String createTableSql = "CREATE TABLE IF NOT EXISTS contacts (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50), phone VARCHAR(20))"; Statement createTableStmt = conn.createStatement(); createTableStmt.execute(createTableSql); createTableStmt.close(); // 插入数据 String insertSql = "INSERT INTO contacts (name, phone) VALUES (?, ?)"; PreparedStatement insertStmt = conn.prepareStatement(insertSql); insertStmt.setString(1, "张三"); insertStmt.setString(2, "13812345678"); insertStmt.execute(); insertStmt.setString(1, "李四"); insertStmt.setString(2, "13987654321"); insertStmt.execute(); insertStmt.close(); // 询数据 String querySql = "SELECT * FROM contacts WHERE name LIKE ?"; PreparedStatement queryStmt = conn.prepareStatement(querySql); queryStmt.setString(1, "%张%"); ResultSet rs = queryStmt.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String phone = rs.getString("phone"); System.out.println(id + "\t" + name + "\t" + phone); } rs.close(); queryStmt.close(); // 更新数据 String updateSql = "UPDATE contacts SET phone = ? WHERE name = ?"; PreparedStatement updateStmt = conn.prepareStatement(updateSql); updateStmt.setString(1, "13212345678"); updateStmt.setString(2, "张三"); updateStmt.execute(); updateStmt.close(); // 删除数据 String deleteSql = "DELETE FROM contacts WHERE name = ?"; PreparedStatement deleteStmt = conn.prepareStatement(deleteSql); deleteStmt.setString(1, "李四"); deleteStmt.execute(); deleteStmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 在这个示例代码中,我们首先创建了一个名为 `contacts` 的通讯录表。然后,我们使用 PreparedStatement 对象插入了两条数据,通过 PreparedStatement 对象询了包含 “张” 字符的数据,使用 PreparedStatement 对象更新了 “张三” 的电话号码,最后使用 PreparedStatement 对象删除了 “李四”的数据。 这个示例代码演示了如何使用 PreparedStatement 对象实现增删功能。在实际开发中,我们需要根据具体的业务需求编写对应的 SQL 语句,并使用 PreparedStatement 对象执行 SQL 语句。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值