When I use the following code it runs perfectly.
PreparedStatement st = con.prepareStatement("select * from users where username=?");
st.setString(1, userId);
ResultSet rs = st.executeQuery();
But when I am using the following code, I get an error that userId (that I pass as parameter) is an invalid column name.
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from users where username="+userId);
Why statement method doesn't work and I have to use PreparedStatement?
User ID is a string (SQL calls this type CHAR or VARCHAR), it must be put in quotes if used in the SQL requests. Like this:
select * from users where username='12345'
PreparedStatement is much better solution because of the SQL injection. You CANNOT just write:
ResultSet rs = st.executeQuery("select * from users where username=\""+userId+"\"");
WRONG CODE - ^^^^^^^^^^^^^^^
because user ID can contains control characters like ['], ["] or [\]. It depends on the SQL server and sometimes are more sophisticated than it looks like. If using PreparedStatement, it is automatically managed by the JDBC driver.
First of all, is better to use the first one. But if you really want to use the second one, you need to put your value into quotes. Simple add the quotes to the value. But is good to create a function to it, if you are going to use it a loot. Like:
public String doubleQuoted(String value){
return "\"" + value + "\"";
}
or
public String singleQuoted(String value){
return "'" + value + "'";
}
and use
ResultSet rs = st.executeQuery("select * from users where username="+singleQuoted(userId));
You need to put strings into quotes:
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from users where username=\'"+userId+"\'");
\ is the escape character.
Note:
Your prepared statement is the preferred way of handling SQL queries. See #30thh answer as to why (SQL Injection attacks).
Related
I want to write a SQL query which contains parameters from a JSP.
I tried it like this
String sqlstring = "\"select"+Activity+" from backgroundcost where onpremprice =' "
+service+" '\"";
PreparedStatement ps = con.prepareStatement(sqlstring);
ResultSet rs = ps.executeQuery();
I'm getting an error.
First of all, I hope you mean that service is a variable that comes from a form of your JSP, that this variable ends up in your Controller and that your controller delegates the access to the database layer to another class.
There are multiple problems with your request :
You use quotes inside your SQL query, you shouldn't.
What is Activity ? probably you miss a space character between ´select´ and the value of `Activity´
The goal of a ´PreparedStatement` is to avoid SQL Injection. You MUST use the code i show below instead of your parameter directly injected in your built SQL statement.
Consider using StringBuilderif you have multiple String concatenations
"
String sqlstring = "select activity from backgroundcost where onpremprice = ?";
PreparedStatement ps = con.prepareStatement(sqlstring);
ps.setString(1, service);
ResultSet rs = ps.executeQuery();
Don't is the short answer. It is a bad design to have database logic in your view. Pass the params from your jsp to a backend java bean en let that fill in the query
make it like this..
String sqlstring = "select * from backgroundcost where onpremprice ='"+service+" '";
PreparedStatement ps = con.prepareStatement(sqlstring);
ResultSet rs = ps.executeQuery();
// in place of * you can put the column name that u need to be selected.
when i write database query :
select * from mytable WHERE subTitle='داتا باللغه العربيه';
it not return any thing but it is found in database table
Since you've included Java as a tag, I'll assume you're using JDBC for connecting to the database, in which case you should never be sending that particular string (SQL statement) to the database.
That is because that particular string implies string concatenation for building the SQL statement, as in:
String subtitle = "داتا باللغه العربيه";
String sql = "select * from mytable WHERE subTitle='" + subtitle + "'";
That is a very big no, no, because it leaves you vulnerable to SQL injection attacks.
Instead, you should be using a PreparedStatement and use parameters markers:
String subtitle = "داتا باللغه العربيه";
String sql = "select * from mytable WHERE subTitle=?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, subtitle);
try (ResultSet rs = stmt.executeQuery()) {
// use result set here
}
}
If this doesn't fix the character set issues you have, try using setNString instead. The 'N' is actually what you likely should have used for the string literal too, as in N'داتا باللغه العربيه', but don't use the string literal.
select * from mytable WHERE subTitle='داتا باللغه العربيه'
I'm searching on the web for several times but did not found anything which could help me (in java).
In fact I need to search in a sql table some rows from some reference which contains an hyphen. The issue made is that the sql replace my reference by the result of a substraction. The type of the columns are string.
Statement stmt = con.createStatement();
String query = "SELECT * FROM WAREHOUSE WHERE REF LIKE('96-18')" ;
Statement statement = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("S_FAMILY"));
}
In this code, it replaces my reference by 78 and does not naturaly return the good result.
I've searched for an escape char but did not found.
Try sending the String as parameter on the query. Doing this requires to change the Statement into PreparedStatement:
String query = "SELECT * FROM WAREHOUSE WHERE REF LIKE(?)" ;
PreparedStatement pstatement = con.prepareStatement(query,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
pstatement.setString(1, "96-18");
ResultSet rs = pstatement.executeQuery();
Note: you should send "96-18" as value of a String variable, do not hard code it.
You can try
SELECT * FROM WAREHOUSE WHERE REF LIKE('96\-18') ESCAPE '\'
Hope it helps
I am trying to use a SQL Select statement for a query in Java. I currently have the following:
ResultSet rs = stmt.executeQuery("SELECT *" +
" FROM " + table +
" WHERE " + selection +
" VALUES " + selectionArgs);
where "selection" is a string and "selectionArgs" is a string array.
String selection = "documentFK=?";
String[] selectionArgs = { ... };
Is it possible to use the VALUES command to replace the ? like in with the INSERT command? Either way, what would be the correct syntax?
Thanks for the help.
I believe what you're looking for is the IN statement. Your query should look like this:
SELECT *
FROM table
WHERE documentFK IN ('doc1', 'doc2', 'doc3')
AND userFK IN ('user1', 'user2', 'user3')
This is (obviously) going to make your code a bit more ugly. You'll have to ensure that the WHERE keyword is used for the first clause, but the AND keyword is used for every other clause. Also, each list will have to be comma-delimited.
no, that is not the way it's done. first you create the statement from the query, using the question marks as place holders for the real values you want to put there. then you bind these values to the statement.
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE documetFK = ?";
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the value
stmt.setInt(1, 4); //1 is "the first question mark", 4 is some fk
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
now, if you want this thing with selection string and some args, then you're going to have a loop in your java code. not sure what your array looks like (you're not giving me that much to go on), but if it's made up from strings, it would be something like this:
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE " + selection;
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the values
for(int i = 0; i < selectionArgs.length; i++) {
stmt.setString(i, selectionArgs[i]); //i is "the nth question mark"
}
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
Can you use a PreparedStatement?
First of all SELECT .. WHERE .. VALUES is incorrect SQL syntax. Lose the VALUES part.
Then you're looking for prepared statements.
In your example it's going to look something like this:
String sql = "SELECT * FROM myTable WHERE documentFK=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
ResultSet rs = pstmt.executeQuery();
Or with multiple parameters:
String sql = "SELECT * FROM myTable WHERE documentFK=? AND indexTerm=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
pstsm.setInt(2, 100); // assume indexTerm can be 100 and is an integer
ResultSet rs = pstmt.executeQuery();
However, all of this doesn't worth your while since you can simply do the same by concatenating the value into the statement. But be aware of the SQL injections, so don't forget to escape the parameters that you're passing into the database.
PS: I was typing this way too long. You already have the answers :-)
As a side note, you may want to take a look at this to prevent SQL injections:
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
Sormula can select using "IN" operator from a java.util.Collection of arbitrary size. You write no SQL. It builds the SQL SELECT query with correct number of "?" parameters. See example 4.
String poster = "user";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM `prices` WHERE `poster`="+poster);
This does not work.Any tips or tricks would be appreciated.
Try surrounding the poster variable with single quotes, like this:
ResultSet rs = stmt.executeQuery("SELECT * FROM `prices` WHERE `poster`='"+poster+"'");
That's because SQL expects strings to be surrounded by single quotes. An even better alternative would be to use prepared statements:
PreparedStatement stmt = con.prepareStatement("SELECT * FROM `prices` WHERE `poster` = ?");
stmt.setString(1, poster);
ResultSet rs = stmt.executeQuery();
It's recommended using PreparedStatement since the way you are currently building the query (by concatenating strings) makes it easy for an attacker to inject arbitrary SQL code in a query, a security threat known as a SQL injection.
1) In general, to "parameterize" your query (or update), you'd use JDBC "prepared statements":
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
2) In your case, however, I think all you need to do is add quotes (and lose the back-quotes):
// This is fine: no back-quotes needed
ResultSet rs = stmt.executeQuery("SELECT * FROM prices");
// Since the value for "poster" is a string, you need to quote it:
String poster = "user";
Statement stmt = con.createStatement();
ResultSet rs =
stmt.executeQuery("SELECT * FROM prices WHERE poster='" + poster + "'");
The Statement interface only lets you execute a simple SQL statement with no parameters. You need to use a PreparedStatement instead.
PreparedStatement pstmt = con.prepareStatement("
select * from
prices where
poster = ?");
pstmt.setString(1, poster);
ResultSet results = ps.executeQuery();