Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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.

share|improve this question

2 Answers 2

up vote 8 down vote accepted

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);
    }
}
share|improve this answer
    
While seemingly correct, I can't say I'm a fan of this answer because it doesn't use try-with-resources where that language construct fits perfectly (and the OP uses it). –  Vulcan yesterday
1  
@Vulcan My company was using Java 6 until like 2 weeks ago...we finally upgraded to Java 7 but let's just say I've been writing code which would compile when Jay Gosling was still a young man. –  Tim Biegeleisen yesterday
    
Don't forget to .execute() your ps... –  glglgl yesterday

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.