将参数传递给 JDBC PreparedStatement [英] Passing parameters to a JDBC PreparedStatement
问题描述
我正在尝试为我的程序创建验证类.我已经建立了与 MySQL 数据库的连接,并且已经将行插入到表中.该表由firstName
、lastName
和userID
字段组成.现在我想通过构造函数的参数选择数据库上的特定行.
I'm trying to make my validation class for my program. I already establish the connection to the MySQL database and I already inserted rows into the table. The table consists of firstName
, lastName
and userID
fields. Now I want to select a specific row on the database through my parameter of my constructor.
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class Validation {
private PreparedStatement statement;
private Connection con;
private String x, y;
public Validation(String userID) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
statement = con.prepareStatement(
"SELECT * from employee WHERE userID = " + "''" + userID);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
x = rs.getString(1);
System.out.print(x);
System.out.print(" ");
y = rs.getString(2);
System.out.println(y);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
但是好像不行.
推荐答案
您应该使用 setString()
方法来设置userID
.这既可以确保语句的格式正确,又可以防止 SQL 注入
:
You should use the setString()
method to set the userID
. This both ensures that the statement is formatted properly, and prevents SQL injection
:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
在 PreparedStatement 的很好的教程rel="noreferrer">Java 教程.
There is a nice tutorial on how to use PreparedStatement
s properly in the Java Tutorials.
这篇关于将参数传递给 JDBC PreparedStatement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!