英文:
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");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论