如何在Java中使用正则表达式替换SQL查询中的表名?

huangapple go评论85阅读模式
英文:

How to replace table name in sql query with regex in Java?

问题

我想在 SQL 查询字符串中替换表名。我只想改变表名。如何在 Java 中使用正则表达式来实现?我不想使用任何依赖库。

例如,

输入:

select ... from table1 where/etc ....

期望输出:

select ... from UPDATED_TABLE_NAME where/etc ....
英文:

I want to replace table name in a sql query string. I only want to change table name. How can I do that in java with regex?

I do not want to use any dependencies.

For example,

Input:

select ... from table1 where/etc ....

expected output:

select ... from UPDATED_TABLE_NAME where/etc ....

答案1

得分: 1

如果您明确地修改查询,就会使自己容易受到 SQL 注入的攻击。您可以使用参数化查询来安全地提供表名,使用 PreparedStatement。

try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM ?")) {
    statement.setString(1, "my_table");
    
    try (ResultSet results = statement.executeQuery()) {
        
    }
}

如果您坚持使用正则表达式,您可以使用上述查询,并将 ? 替换为表名。但我不建议在生产环境中这样做。

String query = "SELECT * FROM ?";

String queryWithTable = query.replaceAll("?", "my_table");
英文:

If you mutate the query explicitly you open yourself to SQL injection. What you could do is use a PreparedStatement with a parameterized query to provide the table name safely.

try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM ?")) {
    statement.setString(1, "my_table");
    
    try (ResultSet results = statement.executeQuery()) {
        
    }
}

If you're insistent on using regex you can just use the query above and replace ? with the table name. I would not do this in a production environment.

String query = "SELECT * FROM ?";

String queryWithTable = query.replaceAll("?", "my_table");

huangapple
  • 本文由 发表于 2020年5月19日 21:03:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/61891745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定