利用已准备的语句正确使用 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