Eliminating quotes in prepared statement in mysql n java - java

I have a prepared statement like this
stmt = select * from table_name where id IN (?);
Once I pass the parameters the stmt looks like way
stmt = select * from table_name where id IN ('1,2,3');
There is no error while executing the query. However the resultset is returned only for the id=1. Is there some way I can eliminate the quotes / get the resultset for all these id's.
stmt = select * from table_name where id IN (?);
select GROUP_CONCAT(id) id from table ;
if(rs.next()){
stmt.setString(1,rs.getString("id"));
stmt.executeQuery();
}
Thanks in advance.

It's not clear what the ID type is, but I believe you should actually be preparing a statement with each possible value as a separate parameter:
select * from table_name where id IN (?, ?, ?)
Then add the three values for the three parameters. It's a common problem with parameterized SQL - when you want to be able to specify a variable number of values, you need to vary the SQL. There may be a MySQL-specific way of coping with this (like table-valued parameters in SQL Server 2008) but I don't believe there's a generic JDBC way of doing this.

Related

SQL State: 42000 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax [duplicate]

I have to add a statement to my java program to update a database table:
String insert =
"INSERT INTO customer(name,address,email) VALUES('" + name + "','" + addre + "','" + email + "');";
I heard that this can be exploited through an SQL injection like:
DROP TABLE customer;
My program has a Java GUI and all name, address and email values are retrieved from Jtextfields. I want to know how the following code (DROP TABLE customer;) could be added to my insert statement by a hacker and how I can prevent this.
You need to use PreparedStatement.
e.g.
String insert = "INSERT INTO customer(name,address,email) VALUES(?, ?, ?);";
PreparedStatement ps = connection.prepareStatement(insert);
ps.setString(1, name);
ps.setString(2, addre);
ps.setString(3, email);
ResultSet rs = ps.executeQuery();
This will prevent injection attacks.
The way the hacker puts it in there is if the String you are inserting has come from input somewhere - e.g. an input field on a web page, or an input field on a form in an application or similar.
I want to know how this kind piece of code("DROP TABLE customer;") can
be added to my insert statement by a hacker
For example:
name = "'); DROP TABLE customer; --"
would yield this value into insert:
INSERT INTO customer(name,address,email) VALUES(''); DROP TABLE customer; --"','"+addre+"','"+email+"');
I specially want to know how can I prevent this
Use prepared statements and SQL arguments (example "stolen" from Matt Fellows):
String insert = "INSERT INTO customer(name,address,email) VALUES(?, ?, ?);";
PreparedStament ps = connection.prepareStatment(insert);
Also parse the values you have on such variables and make sure they don't contain any non-allowed characters (such as ";" in a name).
You can check THIS article for info on that! :)
I recommend Parameterized Queries:
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
An attacker just has to enter something like 'foo#example.com"); DROP TABLE customer; into the field for email and you are done.
You can prevent this by using the proper escaping for JDBC Statements.
That's why you should be using question marks in your string statements:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)
quoted from here
As explained in this post, the PreparedStatement alone does not help you if you are still concatenating Strings.
For instance, one rogue attacker can still do the following:
call a sleep function so that all your database connections will be busy, therefore making your application unavailable
extracting sensitive data from the DB
bypassing the user authentication
And it's not just SQL, but JPQL and HQL can be compromised if you are not using bind parameters:
PreparedStatement ps = connection.prepareStatement(
INSERT INTO customer(name,address,email) VALUES(?, ?, ?)
);
int index = 0;
ps.setString(++index, name);
ps.setString(++index, address);
ps.setString(++index, email);
ResultSet rs = ps.executeQuery();
Bottom line, you should never use string concatenation when building SQL statements. Use a dedicated API for that purpose:
JPA Criteria API
jOOQ
Go for PreparedStatement
Advantages of a PreparedStatement:
Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.
Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the value
You should also limit the privileges of the account that accesses the database as tightly as possible. For example, for searching, the account only needs to have read access to those tables and columns that are required. This will prevent any damaging SQL injection and limit access to sensitive data.
Even though all the other answers tell you as how can you fix SQL injections in Java, answer by Mukesh Kumar actually tells you as who is actually preventing these kind of attacks. Understand that its actually DB server which is preventing SQL injection attacks provided you as a programmer follow their recommendation of using parametrized queries.
Refer Here - Preventing SQL Injection Vulnerabilities
It wouldn't be possible for Java programmer to sanitize each & every input String so DB vendors have given us options of Prepared Statements and they tell us to prepare & execute queries by using that & rest of the things will be taken care of by the DB vendor.
Things as drastic as DROP TABLE customer; might not happen but basic premise of SQL injection is that nobody should be able to break your query by just providing invalid input ( either intentional or non - intentional ).
OWASP - SQL Injection Prevention Cheat Sheet

Using MySQL select in Java as String

I have problem with executing query in my Java program. Here is the code:
String selected=offersList.getSelectedValue();
String sql="SELECT * from outcoming_offers where about='"+selected+"'";
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
And when there is single quotes in 'selected' - it is giving me an error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near.....
So I understand why there is error but I am wondering how to make this work. Are there any other ways except concat()?
It's always better approach is to use prepared statements instead of raw SQL string concatenation.
From your example you should write prepared query like below (parameter to pass are replaced with question marks):
String sql="SELECT * from outcoming_offers where about=?";
PreparedStatement ps = con.preparedStatement(sql);
And then just inject parameter values and execute query:
ps.setString(1, selected);
ResultSet rs = ps.executeQuery();
Thanks to this approach you don't have to deal with SQL query string and single quotes, which is very often error-prone and also (very important) your code is not expose to SQL Injection attacks.
More info in documentation: https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html
You are using a Prepared Statement but not passing the required parameter as you should. Change the statement to this:
String sql="SELECT * from outcoming_offers where about=?";
and then pass the parameter:
pst=con.prepareStatement(sql);
pst.setString(1, selected);
This way you set selected as the 1st parameter of the Prepared Statement.
Now you can execute the query:
rs=pst.executeQuery();

Running PreparedStatement with Like clause with wildcard

I'm trying to execute following SQL query where it tries to find results that matches the column2 values ending with abc
PreparedStatement stmt = conn.prepareStatement("SELECT column1 FROM dbo.table1 WHERE column2 LIKE ?");
stmt.setString(1, "%" +"abc");
But it returns nothing even though there is a matching value. This only happens with SQL Server. Same query with informix database returns correct results. Anyone has an idea about what causing this to behave differently?
Is this due to an issue in how PreparedStatement creates the SQL query for SQL Server?
Edit
I found out this happens when the data in the column which i perform the like contain space. eg: when the column contains "some word" and if i perform the search by stmt.setString(1, "%" + "word"); it won't return a matching result but if i perform the same on for "someword" it would return the matching result
SQL Server accepts wild characters in the LIKE clause within the single quotation marks, like this ''.
A sample SQL query:
SELECT NAME FROM VERSIONS WHERE NAME LIKE 'Upd%'
The query above will yield you results on SQL Server. Applying the same logic to your Java code will retrieve results from your PreparedStatement as well.
PreparedStatement stmt = conn.prepareStatement("SELECT NAME FROM VERSIONS WHERE NAME LIKE ?");
stmt.setString(1, "Upd%");
I've tested this code on SQL Server 2012 and it works for me. You need to ensure that there are no trailing spaces in the search literal that you pass on to your JDBC code.
Though as a side note, you need to understand that a wildcard % used in the beginning, enforces a full table scan on the table which can deteriorate your query performance. A good article for your future reference.
Hope this helps!
i have same problem,i have done with the CONCATE function for this.
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
ps.setString(1, notes);
ResultSet rs = ps.executeQuery();

How to use a PreparedStatement as a subquery in another prepared statement

I'm using a PreparedStatement in my code to make queries. For example:
PreparedStatement stmt = db.con.prepareStatement("select id from nodes where x>? and x<? and y>? and y<?");
stmt.setDouble(1, x1);
... //set a value for each param 1 thru 4
And now I have another query that wants to use the exact same query above as a subquery. So I could do:
PreparedStatement stmt2 = db.con.prepareStatement("select id from edges where startNodeId in
(select id from nodes where x>? and x<? and y>? and y<?)");
But that's repetitive and I'm likely to modify the first PreparedStatement and want those changes to propagate to the second one. Is there a way to set a prepared statement to be a subquery in another statement?
Perhaps something akin to stmt2.setPreparedStatement(2, stmt)?
Simply combine both the queries into one single SELECT statement.
SELECT x,y,z FROM tablez WHERE id IN (SELECT id FROM "your first query")

Error with simple Parameterized Query - Java/ SQL

Following on from one of my previous questions to do with method design I was advised to implemented my SQL queries as a parameterized query as opposed to a simple string.
I've never used parameterized queries before so I decided to start with something simple, take the following Select statement:
String select = "SELECT * FROM ? ";
PreparedStatement ps = connection.prepareStatement(select);
ps.setString(1, "person");
This gives me the following error: "[SQLITE_ERROR] SQL error or missing database (near "?": syntax error)"
I then tried a modified version which has additional criteria;
String select = "SELECT id FROM person WHERE name = ? ";
PreparedStatement ps = connection.prepareStatement(select);
ps.setString(1, "Yui");
This version works fine, in the my first example am I missing the point of parameterized queries or am I constructing them incorrectly?
Thanks!
Simply put, SQL binds can't bind tables, only where clause values. There are some under-the-hood technical reasons for this related to "compiling" prepared SQL statements. In general, parameterized queries was designed to make SQL more secure by preventing SQL injection and it had a side benefit of making queries more "modular" as well but not to the extent of being able to dynamically set a table name (since it's assumed you already know what the table is going to be).
If you want all rows from PERSON table, here is what you should do:
String select = "SELECT * FROM person";
PreparedStatement ps = connection.prepareStatement(select);
Variable binding does not dynamically bind table names as others mentioned above.
If you have the table name coming in to your method as a variable, you may construct the whole query as below:
String select = "SELECT * FROM " + varTableName;
PreparedStatement ps = connection.prepareStatement(select);
Parameterized queries are for querying field names - not the table name!
Prepared statements are still SQL and need to be constructed with the appropriate where clause; i.e. where x = y. One of their advantages is they are parsed by the RDMS when first seen, rather than every time they are sent, which speeds up subsequent executions of the same query with different bind values.

Categories

Resources