利用已準備的語句正確使用 WHERE 條件以確定 MySQL Java 中的任何值
為此,你可以在 Java 中使用 PrepareStatement。以下是語法 -
String anyVariableName="select yourColumnName from yourTableName where name = ?"; PreparedStatement ps = (PreparedStatement) con.prepareStatement(yourVariableName); ps.setString(yourColumnIndex, yourValue);
讓我們建立一個表 -
mysql> create table demo37 −> ( −> id int not null auto_increment primary key, −> name varchar(200) −> ); Query OK, 0 rows affected (2.46 sec)
使用 insert 命令向表中插入一些記錄 -
mysql> insert into demo37(name) values('John');
Query OK, 1 row affected (0.09 sec)
mysql> insert into demo37(name) values('Bob');
Query OK, 1 row affected (0.08 sec)
mysql> insert into demo37(name) values('John');
Query OK, 1 row affected (0.09 sec)
mysql> insert into demo37(name) values('Chris');
Query OK, 1 row affected (0.08 sec)
mysql> insert into demo37(name) values('David');
Query OK, 1 row affected (0.12 sec)
mysql> insert into demo37(name) values('John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into demo37(name) values('Mike');
Query OK, 1 row affected (0.09 sec)使用 select 語句顯示錶中的記錄 -/p>
mysql> select *from demo37;
這將生成以下輸出 -
+----+-------+ | id | name | +----+-------+ | 1 | John | | 2 | Bob | | 3 | John | | 4 | Chris | | 5 | David | | 6 | John | | 7 | Mike | +----+-------+ 7 rows in set (0.00 sec)
示例
以下是 PrepareStatement 的 Java 程式碼 -
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class PrepareStatementDemo {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://:3306/sampledatabase", "root", "123456");
String query = "select name from demo37 where name = ?";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.setString(1, "John");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}輸出
這將生成以下輸出 -
John John John
以下是輸出的快照 -

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP