我正在尝试为我的程序制作验证课程.我已经建立了与MySQL数据库的连接,我已经在表中插入了行.该表由firstName,lastName和userID领域.现在我想通过构造函数的参数在数据库中选择一个特定的行.
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它似乎不起作用.
Kep*_*pil 40
您应该使用该setString()方法来设置userID.这既可以确保语句格式正确,又可以防止SQL injection:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
Run Code Online (Sandbox Code Playgroud)
有一个关于如何PreparedStatement在Java教程中正确使用s的很好的教程.
小智 6
这样做,也可以防止SQL注入攻击
statement = con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
Run Code Online (Sandbox Code Playgroud)
您的查询有问题..
statement =con.prepareStatement("SELECT * from employee WHERE userID = "+"''"+userID);
ResultSet rs = statement.executeQuery();
Run Code Online (Sandbox Code Playgroud)
您正在使用 Prepare Statement .. 所以您需要使用statement.setInt()或statement.setString()根据您的类型来设置参数userId
替换为:-
statement =con.prepareStatement("SELECT * from employee WHERE userID = :userId");
statement.setString(userId, userID);
ResultSet rs = statement.executeQuery();
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用?代替命名值 - :userId..
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
Run Code Online (Sandbox Code Playgroud)
您可以使用 '?' 使用PreparedStatments 在字符串中设置自定义参数。
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
Run Code Online (Sandbox Code Playgroud)
如果您直接在查询中传递 userID,那么它可能会受到SQL INJECTION Attack 的攻击。
如果您使用的是准备好的语句,您应该像这样使用它:
"SELECT * from employee WHERE userID = ?"
Run Code Online (Sandbox Code Playgroud)
然后使用:
statement.setString(1, userID);
Run Code Online (Sandbox Code Playgroud)
?将在您的查询中替换为传递给setString方法的用户 ID 。
看看这里如何使用PreparedStatement。
| 归档时间: |
|
| 查看次数: |
83156 次 |
| 最近记录: |