Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting variable into SQL query from Java

Tags:

java

mysql

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.

like image 902
Jacob Macallan Avatar asked Jul 20 '15 03:07

Jacob Macallan


People also ask

Can I pass a variable to SQL query?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

How do you DECLARE a variable in SQL query?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.

How do you pass a variable in an insert statement in SQL?

This selects from on table and inserts into another... Then my insert statement to be something like this: INSERT INTO table2 (column1, column2, column3, ...) SELECT *@MY_NAME*, column2, column3, ...

How can I use Java and SQL together?

STEP 1: Allocate a Connection object, for connecting to the database server. STEP 2: Allocate a Statement object, under the Connection created earlier, for holding a SQL command. STEP 3: Write a SQL query and execute the query, via the Statement and Connection created. STEP 4: Process the query result.


2 Answers

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);
    }
}
like image 155
Tim Biegeleisen Avatar answered Sep 18 '22 17:09

Tim Biegeleisen


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.

like image 38
Eric Guan Avatar answered Sep 21 '22 17:09

Eric Guan