将变量添加到 Java 中的 sql 语句中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5373921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:49:14  来源:igfitidea点击:

Adding a variable into a sql statement in Java

javasql

提问by Big_A

I am trying to write a sql statement in java that uses a string variable in the where clause. I have tries multiple ways to do this but it keep telling me that I am not using the proper syntax. Can someone please tell me the right way to do this? The variable in this query is par_id.

我正在尝试在 java 中编写一个在 where 子句中使用字符串变量的 sql 语句。我尝试了多种方法来做到这一点,但它一直告诉我我没有使用正确的语法。有人可以告诉我正确的方法吗?此查询中的变量是 par_id。

String sql2 = "SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id =+"'par_id'"+ORDER BY creation_time asc";

String sql2 = "SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id =+"'par_id'"+ORDER BY creation_time asc";

回答by objects

Use a PreparedStatement

使用 PreparedStatement

PreparedStatement ps = connection.prepareStatement("SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id = ? ORDER BY creation_time asc");
ps.setObject(1, par_id);

回答by developer

PreparedStatement ps = connection.prepareStatement(
    "SELECT * FROM Tennis1294966077108.container_tbl " +
    "WHERE parent_id = ? ORDER BY creation_time asc");
ps.setInt(1, par_id); 

回答by Akki

String sql2 = "SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id='"+par_id+"'
ORDER BY creation_time asc";

回答by James Anderson

Try:

尝试:

"SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id = '" 
+ par_id 
+ "' ORDER BY creation_time asc";