Select query on DB2-SQL failing - sql

I am very familiar with MYSQL. Right now, trying a query on IBM SQL DB(DB2) :
"select displayname from HOMEBASEDAPP.LOGINDB where username = '" + username +"' and password = '" + password +"';"
This is the error I get when I run the query.
error occurred [IBM][CLI Driver][DB2/LINUXX8664] SQL0206N "USERNAME" is not valid in the context where it is used. SQLSTATE=42703
I have attached a screenshot of how my table looks :

Your query is failing because DB2 expects all database objects to be uppercase by default. So much so, that it automatically translates your lower-case column names in your query to uppercase before execution.
Since your column names are lowercase, this query fails.
My recommendation is to convert your column names to uppercase, as this will save you much pain in the long run.
However, simply wrap the column names within your query in double-quotes and DB2 will preserve the correct case, and the query should work.
I believe this will work:
SELECT "displayname" FROM HOMEBASEDAPP.LOGINDB WHERE \"username\" = '" + username +"' AND \"password\" = '" + password +"';"
Note: your query here is extremely insecure and is open to SQL injection attacks among other things. Hopefully you plan to use a driver within your app that will allow you to 'prepare' your query and provide means to simply pass in values as parameters.

you need to modify your sql script ,otherwise on finding the first occurrence of double quote,db2 will treat it as terminating character,I mean to say query will be executed till below,so that you will get error:
db2 "select displayname from HOMEBASEDAPP.LOGINDB where username = '"
You need to take care of double quotes for parsing of full sql query, for detail below is a sample reference link:
http://www.justskins.com/forums/insert-with-double-quote-148522.html

Related

After adding Typeorm to My project I cannot make postgresql queries

Whenver I go to my pgAdmin query console and fire a query then I am not able to query the tables created by TypeOrm
But whenever I am adding a where clause it does not allow me to query
Can someone guide me why can't I query or what mistake am I making here?
You are mixing up " and '. You have to use " for identifiers (like tablenames, "User"), but normal strings have to be surrounded with ' ('Hey').
So the correct version of you statement is:
SELECT *
FROM "User"
WHERE name = 'Hey';
Small sidenote: It is mostly seen as bad practice to use upper-case identifiers, as you need to quote them with " always. Usually, the tablename would be user and you can refer to it using user or User.

How To Make MSSQL Ignore The " ' " Inside The Value User Is Giving?

I am doing an insert operation from C# and everything goes well except that one insert statement where the user writes something like "roomie's books" in a value because of the ' operator. How can i make Sql ignore the ' inside values?
They're called parameterized queries.
You probably have something like this:
string sql = "SELECT * FROM Bookstores WHERE StoreName = '" + txtStoreName.Text + "'";
That is very bad! Imagine if the user had typed in something like ';DROP TABLE Bookstores; -- instead of roomie's books.
What you need to do is this:
string sql = "SELECT * FROM Bookstores WHERE StoreName = #StoreName";
using (var cn = new SqlConnection("connection string here"))
using(var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#StoreName", SqlDbType.NVarChar, 50).Value = txtStoreName.Text;
}
That assumes you're using raw ADO.Net objects. If you have an ORM like EntityFramework or Dapper the mechanisms for using parameters will look a little different.
The important thing is, the txtStoreName.Text value is NEVER directly substituted into the SQL code, not even on the server. It's sent to the server separately from the SQL, so there's no possibility of ever contaminating the SQL with user input. You need to fix EVERY QUERY in your application work this way; anything less is practically begging to get hacked, and this is one of those things that's too important to even do wrong for learning or prototypes.
This also tends to perform better, because it allows the server parse the query code once and cache the execution plan.
Joel gave the right answer, but for completeness' sake, I would would like to add that you can escape the ' character in a string literal in T-SQL by adding another one.
So, for instance
INSERT INTO BookStores ([Name]) VALUES ('Roomie''s Books')
But like Joel said, you should never do this, especially for user-entered data, and use parameters when passing data to SQL Server from code instead.

Why do Parameterized queries allow for moving user data out of string to be interpreted?

From https://en.wikipedia.org/wiki/Code_injection#Preventing_problems
To prevent code injection problems, utilize secure input and output handling, such as:
Using APIs that, if used properly, are secure against all input characters. Parameterized queries (also known as "Compiled queries", "prepared statements", "bound variables") allows for moving user data out of string to be interpreted. Additionally Criteria API[7] and similar APIs move away from the concept of command strings to be created and interpreted.
I was wondering how and why "parameterized queries (also known as "Compiled queries", "prepared statements", "bound variables") allows for moving user data out of string to be interpreted" and prevent or mitigate code injection problems?
Can you also provide some examples in explanation?
Thanks.
Compiled queries use special syntax that the database understands. They usually add placeholders for parameters such as in:
select * from applicant where name = ?
select * from applicant where name = :name
The exact syntax depends on the specific technology: JDBC, ODBC, etc.
Now, once those queries are sent to the database (without the specific parameter values), the database "saves" them. Later on (usually in the same database session), you can run them many times, by just providing the parameter values each time.
SQL Injection Safety
They are also safe against SQL injection. For example, if in the previous query instead of a simple value such as Mary you used the value x'; delete from applicant; -- the database will work safely. It would run something like:
select * from applicant where name = 'x; delete from applicant; --'
This query won't probably find anything and will be safe.
If instead you didn't use compiled query, but just decided to concatenate the SQL as a string you would do something like:
String sql = "select * from applicant where name = '" + param1 + "'";
And would end up with the UNSAFE query:
select * from applicant where name = 'x'; delete from applicant; --
This one would run two queries. The second one will delete all the information from your table. Probably not what you want.

Talend: Query Database with Strings/Parameters already defined

How can I perform a Query to my Database (using tOracleInput), like a Select, and use Strings that are already defined as parameters in other components, for example in a 'tFlowToIterate' ?
For example: "SELECT * from TABLE_X where FIELD_X= ? ;"
My '?' is the variable that comes from my tFlowToIterate component (foo). I already tried with (String)globalMap.get("foo"), and other similar forms...
Thanks
[Talend Open Studio for Data Integration v5.3.1;
DB: Oracle]
You answered by yourself. tOracleInput component accepts the query as parameter. This is a very boring java String, no more, no less. This means that if you want to use a globalMap element inside a query, you just need to do a java String concatenation. Something like that:
"SELECT * from TABLE_X where FIELD_X='" + (String)globalMap.get("foo") + "'"
but this won't work (look carefully at the quotes):
"SELECT * from TABLE_X where FIELD_X='(String)globalMap.get("foo")'"
Keep in mind that if you write a query using string concatenation and external vars, the query editor will probably going to mess all the quotes, generating a broken query.
As a general advice, I never suggest to use the "*" operator inside a database input component like tOracleInput. Talend has a fixed-scheme structure that is generated at compile time. This means that if one day you'll add a column to TABLE_X, your ETL will going to fail.
A more robust solution is the following:
Write down your query with the * operator
Click "Guess Schema" to retrieve the table schema and put in your component metadata
Now click "Guess Query" to explicitely rewrite your SELECT
Fix the query (ie. WHERE conditions,...) if needed
You just need to concatenate it with your variable.
So in your case it would look like:
"SELECT *
FROM TABLE_X
WHERE FIELD_X = '" + (String)globalMap.get("foo") + "'"

SQL Injection, simplest solution

I'm unsure how someone would break my SQL if I simply replace all incoming single quotes with double quotes. Can someone enlighten me for both Oracle and SQL Server examples? Thanks.
string sql1 = "select * from users where user_id = '" + "O'Reily".Replace("'", "''").Replace("\", "") + "'";
==> "select * from users where user_id = 'O''Reily'
string sql2 = "select * from users where user_id = '" + "O'''Reily".Replace("'", "''").Replace("\", "") + "'";
==> "select * from users where user_id = 'O''''''Reily"
UPDATE: the slash '\' is a restricted character in the application and will be stripped out before it is used in the query. A double dash can just as easily be added to this list of restricted characters.
Parameterize your variables. Seriously. All modern environments have facilities to do so and you don't have to worry about escape sequences like \' which will turn into \'' with your scheme (in Oracle) which becomes an escaped quote and a regular (terminating) quote.
There are plenty of other tricks to pull this off which I'm not enumerating as they aren't helpful.
Again: Parameterize your variables. Seriously. If you won't learn how to use the parameterization you will become another hacked statistic.
EDIT: Read the links in Paul's answer and here is another: http://unixwiz.net/techtips/sql-injection.html
No matter how clever you think your sanitation of strings is, you are doing it wrong. Especially if you have to handle multiple back ends.
Composing queries out of strings is one of the few things I will flat out fire people for... the risk such a programmer poses to the company is greater than just about anything else they bring to the table (especially after we make it very clear we won't accept such code on day one and provide an entity framework that makes such things unnecessary).
To prevent SQL injection, what you really should do is use bound positional or named parameters instead of constructing your SQL as a string with the user input inlined. How this is done depends on how your application accesses the database. For example, here is what it would look like in Java using JDBC:
Bad:
String updateString = "UPDATE COFFEES SET SALES = 75 " +
"WHERE COF_NAME LIKE 'Colombian'";
stmt.executeUpdate(updateString);
Good:
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate():
I borrowed the example from here:
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
Your proposed solution is vulnerable to the inclusion of the \' string, which would end your quoted section and allow the injection of other commands.
You want to use SQL prepared statements wherever possible, which should be everywhere. Basically, you write your sql with specific placeholders for your data, and then pass that data via a separate, non-interpreted channel to the sql server.
A few links:
http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
http://mattbango.com/notebook/web-development/prepared-statements-in-php-and-mysqli/
There are some tricks involving the attacker taking advantage of the application truncating input :
http://www.rampant-books.com/t_super_sql_154_ideas_prevent_injection.htm