Inserting variable into SQL query from Java

本小妞迷上赌 提交于 2021-02-08 12:20:00

问题


How do you insert variables into an SQL Query?

This is what I have so far ...

public String getBugList(int amount) {
    Connection con  = DatabaseConnection.getConnection();
    try (PreparedStatement ps = con.prepareStatement("SELECT submitter, report FROM bugs_log ORDER BY id DESC limit ))
}

I'm trying to get "amount" bugs to list. So if I input 2, then only the top 2 will get listed.


回答1:


Try this code:

public String getBugList(int amount) {
    Connection con  = DatabaseConnection.getConnection();
    String query = "SELECT submitter, report FROM bugs_log ORDER BY id DESC limit ?";
    try(PreparedStatement ps = con.prepareStatement(query)) {
        ps.setInt(1, amount);
    }
}



回答2:


Put a ? at the desired variable location. Then, from this API, call the set method for the variable type.

http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html

In your case you want an int, so call ps.setInt(1,x). If you want multiple variables, - or in SQL terms a "parameter" - , just use multiple ?'s. The PreparedStatement setter methods requires the parameters index. The max index is equal to the amount of ?'s you have in your query.



来源:https://stackoverflow.com/questions/31508363/inserting-variable-into-sql-query-from-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!