将参数传递给JDBC PreparedStatement

编程入门 行业动态 更新时间:2024-10-22 14:31:50
本文介绍了将参数传递给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

本文发布于:2023-10-27 11:27:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533221.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   JDBC   PreparedStatement

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!