I am using java to connect with oracle.This is the code which I have used
public List<FavouriteShop> getmyfavouriteshop(String username) {
List<FavouriteShop> res=null;
res = this.getJdbcTemplate().query("select * from(Select tbl_orderdetails.branch_name as myfavourite,tbl_orderdetails.branch_id as branch_id from tbl_orderdetails inner join tbl_ordermaster on tbl_orderdetails.order_master_id=tbl_ordermaster.ordermasterid where tbl_ordermaster.user_id='"+username+"' group by tbl_orderdetails.branch_name,tbl_orderdetails.branch_id order by count(tbl_orderdetails.branch_name) desc) where rownum<=3", new MyFavourite());
return res;
}
private class MyFavourite implements RowMapper<FavouriteShop> {
public FavouriteShop mapRow(ResultSet rs,int i) throws SQLException {
FavouriteShop g=new FavouriteShop();
g.setBranch_id(rs.getString("branch_id"));
g.setMyfavourite(rs.getString("myfavourite"));
return g;
}
}
I tried to execute same query in oracle I am getting output but not here and I am getting only empty result.
First, you have a possible SQL injection. You can avoid this by giving username as an argument to query
this.getJdbcTemplate().query("select * from (... where tbl_ordermaster.user_id=? ...) where rownum<=3",
new Object[]{ username }, new MyFavourite());
A possible reason for the empty result might be
... where tbl_ordermaster.user_id='"+username+"' ...
Usually, user_id is an integer value, but you compare it to a String and enclose it in quotes. Passing username as an argument to query as shown above, should already take care of this.
Usually it is not the same query or not the same database :)
Extract your query text to separate variable, print it to logs. Then copy-paste from logs to sql developer.
And check database and user name.
Also, it is possible that you inserted that entries but forgot to add COMMIT.
Related
I want to generate SQL using MessageFormat so that same string can be used by many users and they just have to pass where clause arguments.
e.g. I want select * from user where name='John' and age=15 and area='JStreet'
I can do it using MessageFormat.format(select * from user where {0}={1} and {2}={3} and {4}={5} ,"name","'John'", "age","15","area","'JStreet'")
But I want it dynamic. Means here I am bounded till {0}-{5} what if I need to add more AND conditions.
How can I do this ?
Do not let the user specify the column names as strings. That makes your code easy to break, and it opens you to a very common and dangerous security vulnerability known as SQL injection. I know you said it’s only “for internal use,” but employees/students can be hackers and it’s always possible one will wish to cause harm.
Instead, represent the columns as enum values. I assume the columns of the user table are fixed, so you can hard-code them in the enum:
public enum UserField {
NAME,
AGE,
AREA
}
As others have mentioned, always use a PreparedStatement when making use of values from end users or from unknown code. You can now use the enums to build that PreparedStatement:
public PreparedStatement createStatement(Map<UserField, ?> values,
Connection conn)
throws SQLException {
Collection<String> tests = new ArrayList<>(values.size());
for (UserField field : values.keySet()) {
tests.add(field.name().toLowerCase() + "=?");
}
String sql;
if (tests.isEmpty()) {
sql = "select * from user";
} else {
sql = "select * from user where " + String.join(" and ", tests);
}
PreparedStatement statement = conn.prepareStatement(sql);
int index = 0;
for (Object value : values) {
statement.setObject(++index, value);
}
return statement;
}
I make a query:
jdbcTemplate.query(sqlQueryForGetNodes, new Object[]{treeId, versionId}, rs -> {
NodeType nodeType = NodeType.get(rs.getInt("NodeTypeId"));
int nodeId = rs.getInt("NodeId");
SmbpTreeSwitchCase switchCase = new SmbpTreeSwitchCase();
switchCase.setSwitchConditionType(getSwitchTypeByNodeId(nodeId));
smbpTreeNodes.add(switchCase);
});
private SwitchConditionType getSwitchTypeByNodeId(int nodeId) {
String sqlQueryForGetSwitchTypeByNodeId = "SELECT SwitchConditionTypeId FROM RE.SwitchCondition sc WHERE sc.NodeId = ?";
return jdbcTemplate.query(sqlQueryForGetSwitchTypeByNodeId, resultSet -> {
return SwitchConditionType.get(resultSet.getInt("SwitchConditionTypeId"));
}, nodeId);
}
And in this query, I need to subquery another table in method getSwitchTypeByNodeId to fill the object with data.
But I'm getting an error:
org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [SELECT SwitchConditionTypeId FROM RE.SwitchCondition sc WHERE sc.NodeId = ?]; Before start of result set; nested exception is java.sql.SQLException: Before start of result set
What am I doing wrong? Tell me how to correctly make a subquery in jdbcTemplate?
I think your two lambdas in your two calls to JdbcTemplate.query have different types and hence are being treated differently by Spring.
The first call, which appears to work, appears to use the overload of the JdbcTemplate.query method that takes a String, an Object[] and a RowCallbackHandler and returns void. In this case, your lambda is a RowCallbackHandler which is called once for each row in the result-set. Spring will be advancing the result-set from one row to the next; it's just up to you to do something with each row.
The second call, however, appears to use the overload of JdbcTemplate.query that takes a String, a ResultSetExtractor and a varargs array of arguments, and returns whatever the ResultSetExtractor returns. When using a ResultSetExtractor, Spring will call you only once and expect you to do all of the handling of the result-set. In particular, you will need to check whether the result-set contains any data at all.
Try modifying your second lambda to something like the following:
return jdbcTemplate.query(sqlQueryForGetSwitchTypeByNodeId, resultSet -> {
if (resultSet.next()) {
return SwitchConditionType.get(resultSet.getInt("SwitchConditionTypeId"));
} else {
// SQL query returned no rows. TODO handle this somehow...
}
});
I have a DropWizard project with 2 database connections: one MySql and one Oracle (v11). The MySql connection and queries work just fine. I'm not getting any data from my Oracle queries and there are no errors in my logs.
My DOA looks like this:
public interface DummyDao {
#SqlQuery(
"select prod_sku, initial_qty, current_qty" +
" from prod_detail" +
" where prod_sku = :skuNumber")
#Mapper(DummyMapper.class)
Dummy getSku(#Bind("skuNumber") String skuNumber);
}
My mapper looks like this. When I added log statements to the mapper, I was able to verify it is never called.
public class DummyMapper implements ResultSetMapper<Dummy> {
public Dummy map(int index, ResultSet r, StatementContext ctx)
throws SQLException {
return new Dummy(
r.getString("prod_sku"),
r.getLong("initial_qty"),
r.getLong("current_qty"));
}
}
The DAO is being initialized in my application's run method via the following code:
public class ProductServiceApplication extends Application<ProductServiceConfiguration> {
DataSource sb_ds;
DBI sb_dbi;
DummyDao dummyDao;
#Override
public void run(
final ProductServiceConfiguration configuration,
final Environment environment) {
sb_ds = configuration.getSbliveDataSourceFactory()
.build(environment.metrics(), "sblive");
sb_dbi = new DBI(sb_ds);
dummyDao = sb_dbi.onDemand(DummyDao.class);
}
}
In order to verify there's nothing wrong with my connection, I temporarily added the following code to my run method and it returns the expected result:
try (Handle h = sb_dbi.open()) {
List<Map<String,Object>> result =
h.select("select initial_qty, current_qty from prod_detail where prod_sku = '10501034520008'");
System.out.println("bootstrap: " + result.toString());
}
Executing my DAO's getSku method with the same parameter returns null.
Can someone tell me what I'm doing wrong or point me to measures I can take to figure out what's causing this? I tried to debug it, but I simply don't know enough about JDBI internals to make any sense of what I'm looking at.
I found the issue. The problem is that the column associated with the bind variable is defined as CHAR(20) -- not VARCHAR(20) -- and the actual parameter value has a length of 14. When I execute the statement directly (using the handle or from SqlDeveloper), it works fine. But when using a prepared statement and bind variables, it's broken.
Padding the parameter out to 20 characters resolves the issue.
I am beginner in android development.
I have a question. what is ?s term used for in explanation below? i got it from the documentation of android developer.
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
Added in API level 1
Convenience method for updating rows in the database.
Parameters
table the table to update in
values a map from column names to new column values. null is a valid value that will be translated to NULL.
whereClause the optional WHERE clause to apply when updating. Passing null will update all rows.
whereArgs You may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings.
Returns
the number of rows affected
Basically its a variable to be filled in later. You should use these everywhere that data is coming from a user, a file, or anything else not hardcoded into the app. Why? Because it prevents security problems due to SQL injection. The variables cannot themselves be SQL, and will not be parsed as SQL by the database. So if all variables sent from users to the db are bind variables you remove that entire class of security issues from the app.
A PreparedStatement supports a mechanism called bind variables. For example,
SELECT * FROM table WHERE id = ?
In the above query, there is a single bind parameter for an id. You might use it (to get a row where id is 100) with something like
String sql = "SELECT * FROM table WHERE id = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 100);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Each ? corresponds, in order, to an index of the sql arguments passed in the method's last String[] whereArgs parameter
public int update (table, values, "age > ? AND age < ?", new String[] { "18", "25"});
The documentation meant literally using '?' in the whereClause statement. Simple example:
rawQuery("select * from todo where _id = ?", new String[] { id });
From the above statement, during execution, the ? will be replaced by the value of variable id.
This mechanism helps prevent SQL Injection.
I know that the only really correct way to protect SQL queries against SQL injection in Java is using PreparedStatements.
However, such a statement requires that the basic structure (selected attributes, joined tables, the structure of the WHERE condition) will not vary.
I have here a JSP application that contains a search form with about a dozen fields. But the user does not have to fill in all of them - just the one he needs. Thus my WHERE condition is different every time.
What should I do to still prevent SQL injection?
Escape the user-supplied values? Write a wrapper class that builds a PreparedStatement each time? Or something else?
The database is PostgreSQL 8.4, but I would prefer a general solution.
Thanks a lot in advance.
Have you seen the JDBC NamedParameterJDBCTemplate ?
The NamedParameterJdbcTemplate class
adds support for programming JDBC
statements using named parameters (as
opposed to programming JDBC statements
using only classic placeholder ('?')
arguments.
You can do stuff like:
String sql = "select count(0) from T_ACTOR where first_name = :first_name";
SqlParameterSource namedParameters = new MapSqlParameterSource("first_name", firstName);
return namedParameterJdbcTemplate.queryForInt(sql, namedParameters);
and build your query string dynamically, and then build your SqlParameterSource similarly.
I think that fundamentally, this question is the same as the other questions that I referred to in my comment above, but I do see why you disagree — you're changing what's in your where clause based on what the user supplied.
That still isn't the same as using user-supplied data in the SQL query, though, which you definitely want to use PreparedStatement for. It's actually very similar to the standard problem of needing to use an in statement with PreparedStatement (e.g., where fieldName in (?, ?, ?) but you don't know in advance how many ? you'll need). You just need to build the query dynamically, and add the parameters dynamically, based on information the user supplied (but not directly including that information in the query).
Here's an example of what I mean:
// You'd have just the one instance of this map somewhere:
Map<String,String> fieldNameToColumnName = new HashMap<String,String>();
// You'd actually load these from configuration somewhere rather than hard-coding them
fieldNameToColumnName.put("title", "TITLE");
fieldNameToColumnName.put("firstname", "FNAME");
fieldNameToColumnName.put("lastname", "LNAME");
// ...etc.
// Then in a class somewhere that's used by the JSP, have the code that
// processes requests from users:
public AppropriateResultBean[] doSearch(Map<String,String> parameters)
throws SQLException, IllegalArgumentException
{
StringBuilder sql;
String columnName;
List<String> paramValues;
AppropriateResultBean[] rv;
// Start the SQL statement; again you'd probably load the prefix SQL
// from configuration somewhere rather than hard-coding it here.
sql = new StringBuilder(2000);
sql.append("select appropriate,fields from mytable where ");
// Loop through the given parameters.
// This loop assumes you don't need to preserve some sort of order
// in the params, but is easily adjusted if you do.
paramValues = new ArrayList<String>(parameters.size());
for (Map.Entry<String,String> entry : parameters.entrySet())
{
// Only process fields that aren't blank.
if (entry.getValue().length() > 0)
{
// Get the DB column name that corresponds to this form
// field name.
columnName = fieldNameToColumnName.get(entry.getKey());
// ^-- You'll probably need to prefix this with something, it's not likely to be part of this instance
if (columnName == null)
{
// Somehow, the user got an unknown field into the request
// and that got past the code calling us (perhaps the code
// calling us just used `request.getParameterMap` directly).
// We don't allow unknown fields.
throw new IllegalArgumentException(/* ... */);
}
if (paramValues.size() > 0)
{
sql.append("and ");
}
sql.append(columnName);
sql.append(" = ? ");
paramValues.add(entry.getValue());
}
}
// I'll assume no parameters is an invalid case, but you can adjust the
// below if that's not correct.
if (paramValues.size() == 0)
{
// My read of the problem being solved suggests this is not an
// exceptional condition (users frequently forget to fill things
// in), and so I'd use a flag value (null) for this case. But you
// might go with an exception (you'd know best), either way.
rv = null;
}
else
{
// Do the DB work (below)
rv = this.buildBeansFor(sql.toString(), paramValues);
}
// Done
return rv;
}
private AppropriateResultBean[] buildBeansFor(
String sql,
List<String> paramValues
)
throws SQLException
{
PreparedStatement ps = null;
Connection con = null;
int index;
AppropriateResultBean[] rv;
assert sql != null && sql.length() > 0);
assert paramValues != null && paramValues.size() > 0;
try
{
// Get a connection
con = /* ...however you get connections, whether it's JNDI or some conn pool or ... */;
// Prepare the statement
ps = con.prepareStatement(sql);
// Fill in the values
index = 0;
for (String value : paramValues)
{
ps.setString(++index, value);
}
// Execute the query
rs = ps.executeQuery();
/* ...loop through results, creating AppropriateResultBean instances
* and filling in your array/list/whatever...
*/
rv = /* ...convert the result to what we'll return */;
// Close the DB resources (you probably have utility code for this)
rs.close();
rs = null;
ps.close();
ps = null;
con.close(); // ...assuming pool overrides `close` and expects it to mean "release back to pool", most good pools do
con = null;
// Done
return rv;
}
finally
{
/* If `rs`, `ps`, or `con` is !null, we're processing an exception.
* Clean up the DB resources *without* allowing any exception to be
* thrown, as we don't want to hide the original exception.
*/
}
}
Note how we use information the user supplied us (the fields they filled in), but we didn't ever put anything they actually supplied directly in the SQL we executed, we always ran it through PreparedStatement.
The best solution is to use a middle that does data validation and binding and acts as an intermediary between the JSP and the database.
There might be a list of column names, but it's finite and countable. Let the JSP worry about making the user's selection known to the middle tier; let the middle tier bind and validate before sending it on to the database.
Here is a useful technique for this particular case, where you have a number of clauses in your WHERE but you don't know in advance which ones you need to apply.
Will your user search by title?
select id, title, author from book where title = :title
Or by author?
select id, title, author from book where author = :author
Or both?
select id, title, author from book where title = :title and author = :author
Bad enough with only 2 fields. The number of combinations (and therefore of distinct PreparedStatements) goes up exponentially with the number of conditions. True, chances are you have enough room in your PreparedStatement pool for all those combinations, and to build the clauses programatically in Java, you just need one if branch per condition. Still, it's not that pretty.
You can fix this in a neat way by simply composing a SELECT that looks the same regardless of whether each individual condition is needed.
I hardly need mention that you use a PreparedStatement as suggested by the other answers, and a NamedParameterJdbcTemplate is nice if you're using Spring.
Here it is:
select id, title, author
from book
where coalesce(:title, title) = title
and coalesce(:author, author) = author
Then you supply NULL for each unused condition. coalesce() is a function that returns its first non-null argument. Thus if you pass NULL for :title, the first clause is where coalesce(NULL, title) = title which evaluates to where title = title which, being always true, has no effect on the results.
Depending on how the optimiser handles such queries, you may take a performance hit. But probably not in a modern database.
(Though similar, this problem is not the same as the IN (?, ?, ?) clause problem where you don't know the number of values in the list, since here you do have a fixed number of possible clauses and you just need to activate/disactivate them individually.)
I'm not confident if there is a quote() method, which was widely used in PHP's PDO. This would allow you a more flexible query building approach.
Also, one of the possible ideas could be creating special class, which would process filter criterias and would save into a stack all placeholders and their values.