将参数传递给JDBC PreparedStatement [英] passing parameters to a JDBC PreparedStatement

查看:137
本文介绍了将参数传递给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);
}
}
}

但似乎没有你应该使用

docs / api / java / sql / PreparedStatement.html#setString%28int,%20java.lang.String%29rel =noreferrer> setString() 设置 userID 的方法。这既可以确保语句格式正确,又可以防止 SQL注入

  statement = con.prepareStatement(SELECT * from employee WHERE userID =?); 
statement.setString(1,userID);

关于如何使用 PreparedStatement 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 PreparedStatements properly in the Java Tutorials.

这篇关于将参数传递给JDBC PreparedStatement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆