如何使用 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:///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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP