SQL select query not working with variable parameter in my servelets - sql

i'm trying to execute following line of code with my servelet in netbeans:
ResultSet rs = stmnt.executeQuery("select * from ZEE.WORDCOUNT where WORD =" + searchTxt);
where searchTxt is String variable.
but it says "Column 'zeeshan' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join . . . . ".
it really works fine, if i provide the hardcoded value instead of variable, as:
ResultSet rs = stmnt.executeQuery("select * from ZEE.WORDCOUNT where WORD= 'zeeshan'");
i'm not getting, what i'm missing?

You are missing the single quotes around the sql string you are constructing. So this should work:
ResultSet rs = stmnt.executeQuery("select * from ZEE.WORDCOUNT where WORD ='" + searchTxt+"'");
Please note that constructing SQL statements in this way is really dangerous, because it opens your application up for SQL injection attacks. Use bind parameters instead.
This will also allow better caching of parsed statements on many rdbms's.

Related

Dynamically change project used in a SQL query

I am using BigQuery, Standard SQL, and I want to dynamically change parts of the FROM clause, such as the project id. I have been looking for a solution for this the last 3 years - the problem has been that parameters cannot be used as inputs in the FROM clause. The benefit would be to create a stored procedure, where the project id can be passed in as an argument and can query the appropriate project. The projects would have the same datasets and table names - this would be our way of building a Master query for easy development and implementation. Instead of changing 15 clients' views, we can change the Stored Procedure once and it will push out the changes to all clients' views. However, I have always gotten hung up on dynamically changing the FROM clause!
For example:
DECLARE ProjectId STRING DEFAULT 'test_project';
SELECT col_1 FROM `#ProjectId.Dataset.Table`;
would always error out due to parameters not being able to be used in the FROM clause. However, I saw a related post on using dynamic SQL to overcome this obstacle. I've been looking into the EXECUTE IMMEDIATE function within BigQuery, as this is what has been cited to be a solution. From that post I attempted to implement in several ways:
Attempt #1:
DECLARE ProjectId STRING DEFAULT 'test_project';
EXECUTE IMMEDIATE CONCAT(
"SELECT * FROM ", #ProjectId, ".DataSet.`Table` " )
^ This gives an error "Query error: Undeclared query parameters at [2:19]"
Attempt #2:
EXECUTE IMMEDIATE CONCAT(
"SELECT * FROM ", #ProjectId, ".DataSet.`Table` " )
USING 'my-project' as ProjectId, 'my-dataset' as DataSet;
^ which gives the error "Query error: Undeclared query parameters at [1:19]"
Third and final attempt was to try declaring the parameter within the EXECUTE IMMEDIATE:
EXECUTE IMMEDIATE CONCAT(
"DECLARE ProjectId STRING DEFAULT 'test_project'; ",
"SELECT * FROM ", #ProjectId, ".DataSet.`Table` " )
USING 'my-project' as ProjectId, 'my-dataset' as DataSet;
^ which, you guessed it, results in the same error "Query error: Undeclared query parameters at [1:19]"
I am reaching out to see if anybody has had success with this? I see the value in the Dynamic SQL statements, and have read the documentation and some examples, but it still doesn't seem to work when trying to dynamically change the FROM clause. Any help is much appreciated, willing to try whatever is thrown out - excited to learn what can be done!
Just remove #:
DECLARE ProjectId STRING DEFAULT 'test_project';
EXECUTE IMMEDIATE CONCAT(
"SELECT * FROM ", ProjectId, ".DataSet.`Table` " )

What this mean " Incorrectly Handled Query Assembly " in SQL injection?

im reading book is about " SQL-injection " so i defaced a title
"Incorrectly Handled Query Assembly" what does this mean? and can you give me a example code ? Thanks.
I think you might have understood SQL injection. Incorrectly Handled Query Assembly seems to mean incorrect construction of query string.
Think of a simple scenario where you have written a query to list the whole details of the (logged in) user. Let us
String part1="SELECT * FROM TRANSACTIONS WHERE TAG=' ";
part2=" ' AND ID=' ";
part3=" ';";
//Constructing query with user inputted tag and user ID
String query=part1+ user_entered_tag + part2 + user_id + part3;
//This is an unsafe construction of query.
If the user enters tag like this:
Abc' OR '2'='2' OR '1'='1
The query will become like this:
SELECT * FROM TRANSACTIONS WHERE TAG='Abc' OR '2'='2' OR '1'='1' AND ID='544678';
If the query is then executed, all the transactions will be fetched.
Thus unauthorized person will have access to data. This happens because a loophole is left in the construction of query. The developer should avoid such injection by adding type checking or using built-in features like prepared statements .

Syntax error in WHERE clause near '?) AND (Date = ?)'

I am trying to send a SQL prepared statement to MySQL DB. This is what I have:
String sql1 = "SELECT idReimbursed_Funds As idReimFunds FROM reimbursedfunds Where ReimFundsName = ? AND Date = ?";
PreparedStatement pstmt1 = conn.prepareStatement(sql1);
pstmt1.setString(1, reimfund.getReimFundsName());
pstmt1.setDate(2, (Date) reimfund.getDate());
ResultSet rs1 = pstmt1.executeQuery(sql1);
while(rs1.next()){
idReimFunds = rs1.getInt("idReimFunds");
}
After googling this problem, I found solutions to use parenthesis around the question marks or the whole where clause such as:
String sql1 = "SELECT idReimbursed_Funds As idReimFunds FROM reimbursedfunds Where (ReimFundsName = ?) AND (Date = ?)";
This didn't work though. I get the same error message that is generated by my original code:
"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 '?) AND (Date = ?)' at line 1.
When I try the SQL statement in MySQL Workbench is works fine. Is there a way to use 2 where clauses with JDBC? I know in other posts people have answered that it has to be sent as two different queries, but I thought I would ask just in case someone else reads this posts and knows of a way. Thank you!
The problem (apart from the Date issue as mentioned by bgp), is the line:
ResultSet rs1 = pstmt1.executeQuery(sql1);
You are trying to execute a query string on a prepared statement, which is not allowed by the JDBC standard (MySQL should actually throw an exception instead of sending it to the server as it currently does, but the end result is the same). The documentation of Statement.executeQuery(String sql) says:
Throws:
SQLException - if a database access error occurs, this method is called on a closed Statement, the given SQL statement produces anything other than a single ResultSet object, the method is called on a PreparedStatement or CallableStatement
(emphasis mine)
The reason is that you want to execute the prepared statement, not any other query. You should call PreparedStatement.executeQuery() (so without a parameter):
ResultSet rs1 = pstmt1.executeQuery();
Pretty sure this is because "Date" is a MySQL keyword (reserved). Call the field something else or escape it with backticks, i.e. `Date`

NHibernate SQL query issue with string parameter

I got a problem with this code:
string sql = "select distinct ruoli.c_tip_usr"
+ " from vneczx_ute_app_trn ruoli"
+ " join vnecyd_ent_prf ind"
+ " on ruoli.c_ent = ind.c_ent"
+ " where ruoli.c_app = :appCode"
+ " and ruoli.c_ute_mat = :matricola"
+ " and ind.t_des_ent = :indirizzo";
var ruoli = session.CreateSQLQuery(sql)
.SetString("appCode", Config.Configurator.Istance.ApplicationCode)
.SetString("matricola", user.Matricola)
.SetString("indirizzo", indirizzoCasella)
.List<string>();
This code is correctly executed, the query logged is correct, and the parameter passed correctly evaluated... but it doesn't return any result at all.
Copying the query from the debug console and executing it directly in an Oracle client application (SQL Developer), it gets 2 results (the results I expect to be right).
I found out that the problem is in the last parameter indirizzo, and should depend on the fact that it contains a special char # (indirizzo is an email address).
So I ended up using this solution:
string sql = "select distinct ruoli.c_tip_usr"
+ " from vneczx_ute_app_trn ruoli"
+ " join vnecyd_ent_prf ind"
+ " on ruoli.c_ent = ind.c_ent"
+ " where ruoli.c_app = :appCode"
+ " and ruoli.c_ute_mat = :matricola"
+ " and ind.t_des_ent = '" + indirizzoCasella + "'";
var ruoli = session.CreateSQLQuery(sql)
.SetString("appCode", Config.Configurator.Istance.ApplicationCode)
.SetString("matricola", user.Matricola)
.List<string>();
But it gives me thrills! Aren't the parameters in a query supposed to handle specifically this situation, and thus handle themselves situations with special char, and so on?
Why here a string concatenation works better that a parametric query?
Isn't there a way to force the NHibernate engine to escape some special char?
Update:
I found out how to solve this particular issue: usign the trim command on the field who raise the problem, the problem disappears.
So last line of my sql string now is:
+ " and trim(ind.t_des_ent) = :indirizzo";
I can't understand why it solves the problem thought. Not the field, nor the variable contains empty chars and copying th query on SQL Developer works in both way.
So we have some luck soving the problem, but we have no idea why now it works?
Any thoughts?
even I was facing the same issue, but your hint using TRIM for column saved my day. Since I was looking for a long time, but not able to figure it out.
Along with that, I was able solve my issue by doing the below changes as well:
We were using CHAR datatype some of the columns which used in the query where clause. This was causing the issue to fetch the data from NHibernate. We changed the data type of that column from CHAR to VARCHAR2 and even updated the data with actual size and removed the TRIM from Where clause, the TRICK WORKED!!!! :)
So, any one face this kind of issue, first check whether you are having any column with CHAR and then change to VARCHAR2.
But one more thing you have to remember is: if you are running your application from ASP.Net Development Server, close it and re-run your application. Since if the opening Asp.Net Development Server and if you make any changes to datatype that will NOT be refreshed in your oracle connection. So, better you close the ASP.Net Development server and then re run the application.
Hope my points will help somebody in future!!
Regards,
Sree Harshavardhana
You are not using parameters in a SQL query if you want SQL parameters use a SQL stored proc

Php mysql statement with set and select

I have a weird problem, when i use the query on phpmyadmin, it works. but when i use using a php script it returns an error.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I tried to troubleshoot and discovered that the problem lies with the set statement.
this is my example code.
$sql = 'set #rank=0; select * from user;';
Please help somebody.
First Run
$sql = set #rank=0;
it will store value of rank
then run:
select * from user;
In sort you need to run both queries separately .
set statement stores values. that can be used by next executing query,
like code below :
$sql ="SET #id:=0";
$Executives=$DB->exec($sql);
$sql = "SELECT #id:=#id+1 as id,pes.* FROM profile_executive_summary as pes where profile_id=".$pid;
$Executives=$DB->fetchAssoc($sql);
See what mysql_error returns after you run mysql_query('...'). That might help. In general, mysql_query only permits one query. You can't separate them by newlines or semicolons. mysqli will do it for you though.