如何使用 JDBC 在 PreparedStatement 的 where 子句中传递值?

jdbcobject oriented programmingprogramming

要使用 PreparedStatement 执行带有 Where 子句的语句,请将子句中的值替换为占位符"?"来准备查询,并将此查询作为参数传递给 prepareStatement() 方法。

String query = "SELECT * FROM mobile_sales WHERE unit_sale >= ?";
//创建 PreparedStatement 对象
PreparedStatement pstmt = con.prepareStatement(query);

稍后,使用 PreparedStatement 接口的 setXXX() 方法将值设置为占位符。

pstmt.setInt(1, 4000);
ResultSet rs = pstmt.executeQuery();

示例

让我们使用 CREATE 语句在 MySQL 数据库中创建一个名为 mobile_sales 的表,如下所示 −

CREATE TABLE mobile_sales (
   mobile_brand VARCHAR(255),
   unit_sale INT
);

现在,我们将使用 INSERT 语句向 mobile_sales 表中插入 11 条记录 −

insert into mobile_sales values('Iphone', 3000);
insert into mobile_sales values('Samsung', 4000);
insert into mobile_sales values('Nokia', 5000);
insert into mobile_sales values('Vivo', 1500);
insert into mobile_sales values('Oppo', 900);
insert into mobile_sales values('MI', 6400);
insert into mobile_sales values('MotoG', 4360);
insert into mobile_sales values('Lenovo', 4100);
insert into mobile_sales values('RedMI', 4000);
insert into mobile_sales values('MotoG', 4360);
insert into mobile_sales values('OnePlus', 6334);

以下 JDBC 程序从 mobile_sales 表中检索单位销售额大于或等于 4000 的记录。

在此示例中,我们使用 PreparationStatement 执行 SELECT 查询,并使用 setter 方法在 WHERE 子句中设置值。

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PreparedStatement_WhereClause {
   public static void main(String args[]) throws SQLException {
      //注册驱动程序
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //获取连接
      String mysqlUrl = "jdbc:mysql://localhost/testDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("连接已建立......");
      //查询单位销售额大于(或等于)4000 的手机品牌
      String query = "SELECT * FROM mobile_sales WHERE unit_sale >= ?";
      //创建PreparedStatement 对象
      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setInt(1, 4000);
      ResultSet rs = pstmt.executeQuery();
      System.out.println("Mobile brands with unit sale greater or equal to 4000: ");
      while(rs.next()) {
         System.out.print("Name: "+rs.getString("mobile_brand")+", ");
         System.out.print("Customer Name: "+rs.getString("unit_sale"));
         System.out.println();
      }
   }
}

输出

Connection established......
Mobile brands with unit sale greater or equal to 4000:
Name: Samsung, Customer Name: 4000
Name: Nokia, Customer Name: 5000
Name: MI, Customer Name: 6400
Name: MotoG, Customer Name: 4360
Name: Lenovo, Customer Name: 4100
Name: RedMi, Customer Name: 4000
Name: MotoG, Customer Name: 4360
Name: OnePlus, Customer Name: 6334

相关文章