将参数传递给JDBC PreparedStatement [英] passing parameters to a JDBC PreparedStatement
问题描述
我正在尝试为我的程序制作验证课程。我已经建立了与MySQL数据库的连接,我已经在表中插入了行。该表由 firstName
, lastName
和 userID
字段组成。现在我想通过构造函数的参数在数据库中选择一个特定的行。
import java.sql。*;
import java.sql.PreparedStatement;
import java.sql.Connection;
公共类验证{
私人PreparedStatement声明;
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注入
: statement = con.prepareStatement(SELECT * from employee WHERE userID =?);
statement.setString(1,userID);
关于如何使用 PreparedStatement $ c $有一个很好的教程c>在 Java教程中正确使用。
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);
}
}
}
but it doesn't seem work.
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);
There is a nice tutorial on how to use PreparedStatement
s properly in the Java Tutorials.
这篇关于将参数传递给JDBC PreparedStatement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!