如何使用 JDBC 在 PreparedStatement 中的 where 子句中传递值?
要使用 PreparedStatement 执行带有 Where 子句的语句。通过用占位符号“?”替换子句中的值来准备查询,然后将此查询作为参数传递给 prepareStatement() 方法。
String query = "SELECT * FROM mobile_sales WHERE unit_sale >= ?"; //Creating the PreparedStatement object 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 的记录。
在此示例中,我们使用 PreparedStatement 执行 SELECT 查询,并使用 set 方法设置 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 { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://127.0.0.1/testDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Query to retrieve the mobile brand with unit sale greater than (or, equal to) 4000 String query = "SELECT * FROM mobile_sales WHERE unit_sale >= ?"; //Creating the PreparedStatement object 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
廣告