2

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.

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

0

4 Answers 4

11

Use a PreparedStatement

PreparedStatement ps = connection.prepareStatement("SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id = ? ORDER BY creation_time asc");
ps.setObject(1, par_id);
Sign up to request clarification or add additional context in comments.

4 Comments

Hey Suresh,Im still getting a null pointer exception with that.
the line of this prepared statement
make sure you have created the connection
Ok so I got it figured out. This line does work. The problem was where I had each query closing. I have multiple queries in the application so the close statement ended up in the wrong place...noob mistake...Thank you very much for all the help! =)
1
String sql2 = "SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id='"+par_id+"'
ORDER BY creation_time asc";

2 Comments

Dont use string concatenation when passing data to a SQL statement. This is vulnerable for SQL injections.
Ok. Thanks for informing!
0
PreparedStatement ps = connection.prepareStatement(
    "SELECT * FROM Tennis1294966077108.container_tbl " +
    "WHERE parent_id = ? ORDER BY creation_time asc");
ps.setInt(1, par_id); 

Comments

-1

Try:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.