Java JDBC Query with variables? - java

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();

Related

PreparedStatement not executing the query

I am trying to move all query executions from Statement to PreparedStatement due to SQL injection. My original issue was with update statement, but I wanted to try it with select statement as well. When I execute the below line of code, the statement returns nothing.
String selectQuery = "select is_enabled, syllabus_id from ic_syllabus where syllabus_id=?";
PreparedStatement pstmt = conn.prepareStatement(selectQuery);
pstmt.setString(1, "25AC1CFB7C1A2CF07F176BD3A296F229");
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
String flag = rs.getString(1);
String sybsId = rs.getString(2);
}
I am using Oracle database and am not getting any exceptions either.

Query doesn't work when parameter's are provided

This Works just fine
conn = DatabaseConnection.getConnection();
stmt = conn.prepareStatement("SELECT * FROM Persons ORDER by firstName Desc");
rs = stmt.executeQuery();
But this one doesn't work
conn = DatabaseConnection.getConnection();
stmt = conn.prepareStatement("SELECT * FROM Persons ORDER by ? ?");
stmt.setString(1, "firstName");
stmt.setString(2, "Desc");
rs = stmt.executeQuery();
Not sure why this would not work. Both my parameters are variables and that's the reason I would want to set it explicitly.
Actually your query converted into something like in case of prepared statement:
SELECT * FROM Persons ORDER by 'firstname' 'Desc'
This behaviour provides protection against SQL injection.
Placeholders (?) in prepared statements are used for column replacement. You cannot set the 'DESC' attribute of ORDER BY using setString method.
From PreparedStatement setString javadocs:
* Sets the designated parameter to the given Java <code>String</code> value.
* The driver converts this
* to an SQL <code>VARCHAR</code> or <code>LONGVARCHAR</code> value
* (depending on the argument's
* size relative to the driver's limits on <code>VARCHAR</code> values)
* when it sends it to the database.
In case you want to take the ORDER as a parameter to your DAO method then simply use String replacement in the query. Maybe like this:
public myDAOMethod(String firstName, String order) {
String query = "SELECT * FROM Persons ORDER by ? " + order;
conn = DatabaseConnection.getConnection(query);
stmt = conn.prepareStatement();
stmt.setString(1, "firstName");
rs = stmt.executeQuery();
}

Getting an error in createStatement

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).

Can have two database connection in one function?

When I debug, I get this error :
Column 'place1' not found.
I was able to verify that it has column place1 in sql.
Is it because I can not have two database connection in one function? I am unsure on how to further debug the problem.
Case.java
System.out.println("The highest value is "+highest+"");
System.out.println("It is found at index "+highestIndex+""); // until now it works fine
String sql ="Select Day from menu where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
int kb=rs.getInt("Day");
System.out.println(kb);
if(kb==k) // k is a value getting from comboBox
{
String sql1 ="Select * from placeseen where ID =?";
DatabaseConnection db1 = new DatabaseConnection();
Connection conn1 =db1.getConnection();
PreparedStatement ps1 = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs1 = ps.executeQuery();
if (rs1.next())
{
String aaa=rs1.getString("place1");
String bbb=rs1.getString("place2");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
DispDay dc=new DispDay();
}
ps1.close();
rs1.close();
conn1.close();
}
else
{
System.out.print("N");
System.out.println("Sorry!!!");
}
}
ps.close();
rs.close();
conn.close();
Trace your code to see where you're getting the data. The error is on this line:
String aaa=rs1.getString("place1");
Where does rs1 come from?:
ResultSet rs1 = ps.executeQuery();
Where does ps come from?:
PreparedStatement ps = conn.prepareStatement(sql);
Where does sql come from?:
String sql ="Select Day from menu where ID =?";
There's no column being selected called place1. This query is only selecting a single column called Day.
Maybe you meant to get the result from the second prepared statement?:
ResultSet rs1 = ps1.executeQuery();
There are probably more such errors. Perhaps several (or many) more. Because...
Hint: Using meaningful variable names will make your code a lot easier to follow. ps, ps1, rs1, etc. are very easy to confuse. Name variables by the things they conceptually represent and your code starts to read like a story which can be followed. Variable names like daysQuery and daysResults and placesResults make it more obvious that something is wrong when you try to find a "place" in a variable which represents "days".
In your second query:
PreparedStatement ps1 = conn.prepareStatement(sql);
you are accidentally using the variable sql instead of your previously defined sql1. Replace it and it will be ok.

Replace query with hyphen by a substraction

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

Categories