1
session.getAttribute('loginId')//giving 1

ResultSet rs=st.executeQuery("select * from interest where loginid='session.getAttribute('loginId')'");

or

ResultSet rs=st.executeQuery("select * from interest where loginid='session.getAttribute("loginId")'");

this is giving me sql Exception.

what wrong in my query? while-

ResultSet rs=st.executeQuery("select * from interest where loginid='1'");

is running fine.

I cant call this by storing loginId in String Object.

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'loginId')'' at line 1

2 Answers 2

2

Pass in the value returned from getAttribute rather than the literal value session.getAttribute('loginId')

PreparedStatement preparedStatement = 
            conn.prepareStatement("select * from interest where loginid=?");
preparedStatement.setString(1, session.getAttribute("loginId"));
Sign up to request clarification or add additional context in comments.

Comments

-1

You have to concat the strings. Not inclusing the parameter in one string:

change to:

ResultSet rs=st.executeQuery("select * from interest where loginid='"+session.getAttribute("loginId")+"'");

Or better use prepared statements. It prevents you for sql injection ans your query will be much more easier to read.

6 Comments

This is a introduces SQL injection and other problems (eg broken queries if they contain a single quote). Never concatenate values into an SQL query, always use parametrized queries.
@MarkRotteveel Why the downvote. The answer is correct and i have pointed to prepared statements. But i do not want to write the code of prepared statement for the op. He/she has to lear it.
I downvoted because it shows the wrong (and as the last 20 years of security incidents caused by SQL injection have shown: dangerous) way of constructing SQL queries. Yes it solves the problem, but it solves it by introducing/reinforcing a dangerous solution.
@MarkRotteveel So you think it is better to rewrite the code for OP with secure prepared statement without saying why like the other answer??
The other answer does both with "Pass in the value returned from getAttribute rather than the literal value" (which - to me - is the same explanation as the first part of your answer). Granted, it could have explained it in more detail.
|

Your Answer

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