I have the following code:
string sql = "SELECT COUNT(*) FROM " + tableName;
var rtn = DapperConnection.Query<int>(sql);
This works and bring back 1 record in the rtn variable. When I inspect the variable it seems to have 2 members, one is "[0]" and the other is "Raw View".
The member [0] is of type int and has the expected value, but I can't seem to get to that value in my code. This seems like a stupid question because I should be able to get to it, but can't. The latest try was the following:
int rtnCount = (int)rtn[0];
This however gave me a compiler error. How do I get to this value in my code?
Please don't do this! It's fragile, and introduces a gaping sql injection vulnerability. If you can return your count for a given table with one line of very expressive code, and no vulnerability, why make it method?
Do this instead:
DapperConnection.ExecuteScalar<int>("SELECT COUNT(*) FROM customers");
// You will be happier and live longer if you avoid dynamically constructing
// sql with string concat.
Use rtn.First() — it is an enumeration so that's the general way to get its first (and only in this case) item.
Related
I have this SQL sentence for retrieving a specific role (by the column RoleID) from the table Roles:
DBBroker.getInstance.read("SELECT * FROM Roles WHERE RoleID='" & role.roleID & "';")
The thing is that when my program runs the sentence, I obtain this error:
I work with a Microsoft Access Database in which RoleID is defined as Autonumber while in my program it is defined as String. Anyway I tried changing Types but it still fails.
I have too much code in the program so I cannot include it here, but I'm open for any requests regarding a specific part of the program.
Thanks
By the way I worked before on another similar database and the exact same clause did work indeed.
Though you solved your problem,i am answering this just to describe and help guys who visit this page in future
Here's a one line explanation of the issue :
The data type you set for the column in the table of the database is different than the type of value you are passing
For example : In simple words, you have a word and a number , can you add them ? I mean in a mathematical way ? The answer is NO.
Now assuming that your data-type for the RoleID column is Integer but role.RoleId is of type/returns value of type String , then there will be a data-type mismatch as one is an integer and the other is a String.
Now, going through the comments , i see that you've solved your issue.Now, let me explain how you solved it.
Your sql query looks like this :
"SELECT * FROM Roles WHERE RoleID='" & role.roleID & "';"
Let's point out the main relevant part :
RoleID='" & role.roleID & "'
Here,before you close the string RoleID= with double quotes, you use '(single quote).In sql-queries, single quotes are used to declare/give a value(of type STRING) to the required/given parameter(of the query).
In order to pass an Integer value ,you can pass it without the ' single quote like this :
RoleID=12345
So, the answer is simple:You were passing some data of type String to a column which expects data/even if the passed value is of type intger but because you were using ' single quotes when passing the values,the quote had converted it to a String ..So, all u have to do(had to do-in your case) is remove the two single quotes(')
Hope this helps to enrich your knowledge :)
I've got a query that should contain a literal at sign (#). How do I express this with a Dapper query?
var num = cnx.Query<int>("declare #foo int = 2; select #foo").Single();
I've tried using literals as a workaround:
var num = cnx.Query<int>(
"declare {=at}foo int = 2; select {=at}foo", new { at = "#" }
).Single();
But this throws a NotSupportedException since string literals aren't supported...
(Note that in my real code, I've got other #parameters that I actually do want replaced and auto-escaped for me, so I'd rather stick with Dapper if possible instead of just using a raw SqlCommand.)
Oh. I figured it out. If you have a #param that isn't actually bound to anything, it's passed as-is to the underlying SqlCommand, which passes it straight to the DB.
In other words, you don't need to do anything special to get this to work. My first example should run fine. Silly me.
I'm wondering if/how this is possible, if it is, I'm sure its a simple fix that I can't seem to figure out
#SqlQuery("SELECT * FROM Table WHERE column LIKE '%:thingName%'")
public Set<Things> getThings(#Bind("thingName", String thingName)
Essentially for this toy example I am trying to select a row where a column contains [any text]thingName[anyText]. When using as above, I think the quotes obscure the bound variable so it literally looks for [any text]:thingName[anyText] and not my bound variable.
Thank you in advance,
Madeline
I use concat to surround input with % signs while still using a bound variable to avoid SQL injection:
#SqlQuery("select * from atable where acolumn like concat('%',:thingName,'%')")
public Set getNames(#Bind("thingName") String thingName);
It appears to be the case that you must add the '%' percentages to the bound variable:
#SqlQuery("SELECT * FROM Table WHERE column LIKE :thingName")
public Set<Things> getThings(#Bind("thingName") String thingName); // where thingName = "%" + thingName + "%"
See also: https://groups.google.com/forum/?fromgroups#!topic/jdbi/EwUi2jAEPdk
Quote from Brian McCallister
Using the :foo binding stuff creates a prepared statement and binds in the value for name in this case. You need the % to be part of the bound value, or you need to not use bindings to a prepared statement.
Approach 1 (the safer and generally better one):
"select … from foo where name like :name" and bind the value ("%" + name)
Approach 2 (which opens you up to sql injection):
"select … from foo where name like '%' " and define("name", name) (or in sql object, (#Define("name") name) -- which puts name in as a literal in your statement.
The key thing is that the % character is part of the value you are testing against, not part of the statement.
This must be the case with LIKE while binding variables. As per JDBI doc(Here) using SQL query concatenation can solve the issue. It worked for me.
I've read thread from 2005 and people said SOQL does not support string concatenation.
Though wondering if it is supported and someone has done this.
I'm trying to concat but no luck :(
Below is APEX code trying to find record with specified email.
String myEmail = 'my#email.com';
String foo = 'SELECT emailTo__c, source__c FROM EmailLog__c
WHERE source__c = \'' +
myEmail + '\';
Database.query(foo)
Even though the record is indeed in the database, it does not query anything. Debug shows
"row(0)" which means empty is returned.
Am I doing concat wrong way?
UPDATE
I just found a way not have to add single quote. Just needed to apply same colon variable even for String that has query.
String foo = DateTime.newInstance(......);
String bar = 'SELECT id FROM SomeObject__c WHERE createdOn__c = :foo';
List<SomeObject__c> result = Database.query(bar);
System.debug(result);
This works too and is necessary if WHERE clause contains DateTime since DateTime cannot be surrounded with single quotes.
Why do you use Database.query()? Stuff will be much simpler and faster if you'll use normal queries in brackets
[SELECT emailTo__c, source__c FROM EmailLog__c WHERE source__c = :myEmail]
Not to mention that parameter binding instead of string concatenation means no need to worry about SQL injections etc.. Please consider getting used to these queries in brackets, they look weird in beginnign but will save your butt many times (mistyped field names etc).
As for actual concatenation - it works like you described it, I'm just unsure about the need to escape apostrophes. Binding the variables is safest way to go.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm
http://www.salesforce.com/us/developer/docs/api/index_Left.htm#CSHID=sforce_api_calls_soql.htm|StartTopic=Content%2Fsforce_api_calls_soql.htm|SkinName=webhelp
I know that dynamic SQL queries are bad due to the SQL Injection issues (as well as performance and other issues). I also know that parameterized queries are prefered to avoid injection issues, we all know that.
But my client is still very stubborn and thinks that just
var UserName=Request.Form["UserName"];
UserName=UserName.Replace("'","''");
SQL="SELECT * FROM Users where UserName='" + UserName + "'";
Is enought protection against SQL injection issues against (SQL Server (Only), not mysql).
Can anyone give me real SQL Injection attack example that still can get through the Replace case above? Guess there's some unicode character issues?
I want some real live examples of attacks that still can get through that simple replace.
My question is only for SQL Server and I know that MySQL has some issues with the \ character.
This will not work if you are using NUMBERs.
"SELECT * FROM data WHERE id = " + a_variable + ";"
using
1;DROP TABLE users
Gives you
SELECT * FROM DATA WHERE id=1;DROP TABLE users;
Have a look at
SQL injection
MSDN SQL Injection
EDIT
Have a look at this. It is very close to your question
Proving SQL Injection
Please input your age : 21; drop table users;
SELECT * FROM table where age = 21; drop table users;
ouchies
I have some trouble understanding the scope of replacement. Your original line is:
SQL=SQL.Replace("''","'");
Because you apply it to the variable name SQL, I would assume you are replacing all occurrences of '' with ' in the entire statement.
This can't be correct: consider this statement:
SELECT * FROM tab WHERE col = '<input value goes here>'
Now, if is the empty string, the statement will be:
SELECT * FROM tab WHERE col = ''
...and after SQL.Replace("''", "'") it will become:
SELECT * FROM tab WHERE col = '
As you can see, it will leave a dangling single quote, and yields a syntax error.
Now, let's suppose you intended to write SQL.Replace("'", "''") then the replaced statement would become:
SELECT * FROM tab WHERE col = ''''
Although syntactically correct, you are now comparing col to a literal single quote (as the '' inside the outer single quotes that delimit the literal string will evaluate to a literal single quote). So this can't be right either.
This leads me to believe that you might be doing something like this:
SQL = "SELECT * FROM tab WHERE col = '" & ParamValue.Replace("'", "''") & "'"
Now, as was already pointed out by the previous poster, this approach does not work for number. Or actually, this approach is only applicable in case you want to process the input inside a string literal in the SQL stament.
There is at least on case where this may be problematic. If MS SQL servers QUOTED_IDENTIFIER setting is disabled, then literal strings may also be enclosed by double quote characters. In this case, user values injecting a double quote will lead to the same problems as you have with single quote strings. In addition, the standard escape sequence for a single quote (two single quotes) doesn't work anymore!!
Just consider this snippet:
SET QUOTED_IDENTIFIER OFF
SELECT " "" '' "
This gives the result:
" ''
So at least, the escaping process must be different depending on whether you delimit strings with single or with double quotes. This may not seem a big problem as QUOTED_IDENTIFIER is ON by default, but still. See:
http://msdn.microsoft.com/en-us/library/ms174393.aspx
Please see this XKCD cartoon:
Little Bobby Tables
The answers so far have been targeting on condition query with numeric datatypes and not having single quote in the WHERE clause.
However in MSSQL *at least in ver 2005), this works even if id is say an integer type:
"SELECT * FROM data WHERE id = '" + a_variable + "';"
I hate to say this but unless stored procedure (code that calls EXECUTE, EXEC, or sp_executesql) is used or WHERE clauses do not use quotes for numeric types, using single quote replacement will almost prevent possibility of SQL Injection. I cannot be 100% certain, and I really hope someone can prove me wrong.
I mentioned stored procedure due to second level injection which I only recently read about. See an SO post here on What is second level SQL Injection.
To quote from the accepted answer of the SO question "Proving SQL Injection":
[...] there is nothing inherently unsafe in a properly-quoted SQL statement.
So, if
String data is properly escaped using Replace("'","''") (and your SQL uses single quotes around strings, see Roland's answer w.r.t. QUOTED_IDENTIFIER),
numeric data comes from numeric variables and is properly (i.e. culture-invariantly) converted to string, and
datetime data comes from datetime variables and is properly converted to string (i.e. into one of the culture-invariant formats accepted by SQL Server).
then I cannot think of any way that SQL injection could be done in SQL Server.
The Unicode thing you mentioned in your question was a MySQL bug. Accounting for such problems in your code provides an extra layer of security (which is usually a good thing). Primarily, it's the task of the database engine to make sure that a properly-quoted SQL statement is not a security risk.
Your client is correct.
SQL = SQL.Replace("'","''");
will stop all injection attacks.
The reason this is not considered safe is that it's easy to miss one string entirely.