gpt4 book ai didi

java - 如何通过用户输入的带条件的表名从oracle数据库中读取数据?

转载 作者:行者123 更新时间:2023-11-30 06:10:19 24 4
gpt4 key购买 nike

我正在尝试从 oracle 数据库中读取数据,用户将在其中输入表名。这里没有问题。但是当我添加任何条件时,它会显示错误。下面给出了代码和堆栈跟踪。

    package jdbc_test;

import java.sql.*;
import java.util.Scanner;

public class JDBC_Test {
public static void main(String[] args) {

String tableName=null;
Scanner input = new Scanner(System.in);
int id=8;

System.out.println("Enter the table name: ");
tableName = input.nextLine();

try
{

Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:oracle12c", "system", "oracle12c");


Statement stmt = con.createStatement();


ResultSet rs = stmt.executeQuery("select * from "+tableName+"where id='"+id+"'");

System.out.printf("%15s%15s","Name","ID");

while (rs.next())
{
System.out.printf("\n%15s",rs.getString("name"));
}

con.close();
stmt.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

控制台:

Enter the table name: 
t

异常(exception):

java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended

如何根据条件读取用户指定表名的数据?

最佳答案

您的示例提供的答案“有效”容易受到 SQL injection attacks 的攻击. 仔细阅读这种危险的做法。因此,我建议您不要使用它。

您想使用 PreparedStatement对于列字段。请仔细阅读准备好的语句的重要性,因为它将为您编写更安全的解决方案的更美好 future 做好准备。


允许用户输入表名不是一个好主意

这不仅不是一个好主意,甚至 PreparedStatement 也不支持它。

您不能在准备好的语句中使用表名作为参数 (?)。您必须找到另一种方法将其放在那里,例如字符串连接,这很危险。

除非您使用预先确定的白名单,否则您不能允许用户选择表名,因为那样会允许 SQL 注入(inject)。

存储库中的凭据是另一个安全风险。

您还应该避免将用户名和密码直接放入 getConnection() 中。使用 secret 管理器,或者至少从未提交到存储库的属性文件中读取(如果使用 secret 管理器加密则加分)。

这是你的固定 try block :

try
{
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oracle12c", username, password);

// You want to prepare a statement so you can pass parameters.
PreparedStatement stmt = con.prepareStatement();

// The first question mark (?)
// Assuming this is an INT type. If not, there is setString, setLong, etc.
ps.setInt(1, id);

// Note the first question mark is where the ID is supposed to be. This is a parameter.
ResultSet rs = stmt.executeQuery("select * from tableName where id = ?");

while (rs.next())
{
// Replace "column_name" with the name of your column
System.out.println(rs.getString("column_name"));
}

con.close();
stmt.close();
}

如果您正在学习编码,无论是谁告诉您按照您的方式去做,都会让您终生陷入非常糟糕的编码实践,这将导致您工作的公司遭到黑客攻击。

关于java - 如何通过用户输入的带条件的表名从oracle数据库中读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35993345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com