Home » SQL Server

Sql injection problem?

hi all,

i am using query like this

select count(*) from Users where username='"+userNameTextBox.Text.Replace("'","''")+"'

in the above simple query sql injection is possible or not (i.e., even after replacing the single quote with two single quotes), if possible how is it possible can any body explain me?

 and more over what is blind sql injection, can any body give example for that?


Burepalli V S Rao.


8 Answers Found


Answer 1

>>select count(*) from Users where username='"+userNameTextBox.Text.Replace("'","''")+"'

yes above query  is subjected to sql  injection, escaping a single  quote with two single quotes  only escape an apostrophe but does not prevent sql injection. Someone can pass  ;drop table TableName

as username as a  textbox values.

see more examples and way to prevent SQL injection  at


>>more over what is blind  sql injection, can any body  give example  for that?

see example and explanation at



Answer 2

no it is not possible , in the above query  if you pass ';drop table tablename' then the entire thing will be taken as string ,above query will become

select count(*) from Users where username=';drop table tablename'

then the above query will be executed without any problem.

so, if anybody knows please give  me some example  for that.


Burepalli V S Rao.


Answer 3

Burepalli V S Rao,

You have a valid point, I did tested it if you replace  single quote  with a double quote then indeed your code is harmless

if you **do not** then  it is subjected to SQL injection  shown below with an example

 in the example  you posted

if the actual textbox username entry is

' ; DROP DATABASE pubs  --

your query  will become

select count(*) from Users where username=''; DROP DATABASE pubs  --'

The; (semicolon) character tells SQL that this is the end of the current statement, which is then followed by the following malicious SQL code.


Finally, the -- (double dash) sequence of characters is a SQL comment that tells SQL to ignore the rest of the text. In this case, SQL ignores the closing ' (single quotation mark) character, which would otherwise cause a SQL parser error.

But if you escape single  quote with double quote then it will throw SQL parser error which will prevent malicious code to be executed.




Answer 4

that is wrong , the above one query  becomes

select count(*) from Users where username =''';DROP DATABASE pubs --';

so, this one will aslo be executed without having any problem

hai shah you are not getting me, see what i am doing is

i am taking the the value from the textbox what ever value i am getting from the textbox first i am replacing  single quote  with two quotes  (if text  contains the single  quote) on top of this text again i am keeping single quotes so, according to me it will work fine

any help please


Burepalli V S Rao.


Answer 5

I'm not going to argue whether it is possible to inject based on your replacement, I would just like to suggest that you adhere to best practice and use parameterized commands, where it is impossible to inject in the first place. That will also buy your huge advantages when it comes to execution plan handling, caching and re-use.

Answer 6

 i too agree with you. but my intention is even after replacing  sql  injection is possible or not  thats it i want to learn it how is it possible thats it nothing else. but what ever you said that is absolutely correct.

Answer 7

To be pefectly 'safe' of sql  injection use parameterized commands as Tibor pointed

Answer 8


Your method will stop anyone passing usning a ' to end a '' statememnt - as you have shown in the examples above.

The porblem will com eif a new developer makes changes to your code - or a new access pages is developed which dosen't you teh replace  method. This may be in two years time etc.

If you use parameterized stored procedures as your access method other developers can work away in saftey.






Hi All, 

Thank you for advance.

Our database affected with SQL Injection.

so We need to create a sql server 2005 new login for SQL Injection prevention

User can perform,
access tables with select,
update and delete queryaccess views,
functions and stored proc
perform cursor   

what are the permissions given for that login account?

can any body explain the difference between normal sql injection and blind sql injection with an example.

Well I was busy using events and for some reason when I compiled it it seemed to give me duplice errors for generic names such as:

error C2011: '__EventingCriticalSectionStub' : 'struct' type redefinition

At first this quite stumped me especially since events involve a lot of things going on behind one's back but through searching on the internet I sort of remembered that you have the ability to display the code the way it is sent to the compiler. Now I wasn't quite able to do this but I did manage to get it to expand the events where I noticed something quite interesting. (If someone could tell me how to get it to output the final code please do tell)

(Do please note that the following contains many assumptions some of which may be wrong please correct me if that is the case.)

It has lots of #inejected_line's which it places either at the top or at the bottom of the header file. Now this would normally be fine since it has a line number and then injects it somewhere else at a certain line number. The problem though is that this code tends to end up before the #pragma once which causes the internal code to be injected into line nr X the number of times it is included. This should theoretically already makes my questions obvious:

Why on earth does it randomly switch between adding the inject lines at the bottom of the header and then at the top?

Can I control this behaviour and if not, how can I resolve my issue without making sure each header only has one include?

I have an application written on MS Visual C++ 6. In one of mu customers (WinXP Japanese) the application fails right after start. After studying crash dump  i saw the following:

My app   in its InitInstance intercepts several user32.dll functions: GetSysColor, GetSysColorBrush, DrawFrameControl. I needed this to implement my own skinning. The interception is performed by widely used 'code injection' method: I locate necessary function in loaded user32.dll and write into its begin byte 0xe9 (command 'jump near'), then 4 bytes - relative address of my intercept function. Before this operation I suspend all threads of my application.

This worked fine on lot of customer's PCs. But on one PC the application fails right after this intercept is done  - after this myapp calls LoadString, and I get Access Violation. Call Stack is:
  <my code that calls CString::LoadStringW>

It turned out - this customer has installed a software named Humming Heads Security Platform (http://www.hummingheads.co.jp/). This is a security monitor that controls many aspects of every application's work. From the crash dump I see: several DLLs of this Humming Heads Security Platform are embedded into my process. My version is: it intercepts API functions too, and this lead to conflict with my interception (somehow). If I turn this interception off in my application, it does not fail. What can you say about:
what exactly happened?
what can I do?
will it help if I will do the API functions interception using other method known as 'Modification of import/export tables'?



I need to display multiple instances of a basketDetailsView.xaml within a region placed in basketView.xaml, but I'm getting the following errormessage when i debug my code:

"An exception occurred while creating a region with name 'basketRegion'. The exception was: System.InvalidOperationException: ItemsControl's ItemsSource property is not empty. This control is being associated with a region, but the control is already bound to something else. If you did not explicitly set the control's ItemSource property, this exception may be caused by a change in the value of the inherited RegionManager attached property"

The basketView XAML contains an ItemsControl tag defined like this:

<ItemsControl x:Name="basketItemsControl" BorderThickness="0" cal:RegionManager.RegionName="basketRegion" Margin="0,10,0,10" />


 The view also has a listbox where I can uncheck/check the BasketDetailsViews I want to look at:


 <ListBox x:Name="basketListBox" ItemsSource="{Binding basket}"  MinWidth="200">
      <CheckBox commands:Checked1.Command="{Binding DataContext.CheckCommand,    ElementName=basketListBox}" Content="{Binding basketName}" ></CheckBox>

 When I run without debugging it executes fine and I can pop in/out the different basketDetailsViews, but when debugging the above mentioned error shows. What Am i doing wrong?


Hello, I use Caliburn.Micto as MVVM framework for my WPF application and also MEF for injection.

UML of my application look like this: http://i54.tinypic.com/2n1b4mx.png

My scenario is: I create in view-model-1 (in  project is LogOnViewModel) new view-model-2 (in my project is MessengerViewModel) with shell-view-model method.

I need pass object from view-model-1 to constructor of view-model-2.

I use MEF on injection class from external assembly which is loaded in boostraper class.

On creation of new view-models I use abstract factory pattern, here is my implementation:

///<summary>/// Factory interfaces///</summary>publicinterface IViewModelFactory
  ILogOnViewModel CreateLogOnViewModel(IShellViewModel shellViewModel);
  IMessengerViewModel CreateMessengerViewModel(IShellViewModel shellViewModel, PokecAccount account);

 ///<summary>/// Concrent implementation of factory///</summary>
 publicclass DefaulFactoryViewModel:IViewModelFactory
  #region Implementation of IViewModelFactory

  //create start up view-modelpublic ILogOnViewModel CreateLogOnViewModel(IShellViewModel shellViewModel)
   returnnew LogOnViewModel(shellViewModel);

  //this method create new view model//it is used in LogOnViewModelpublic IMessengerViewModel CreateMessengerViewModel(IShellViewModel shellViewModel, PokecAccount account)
   returnnew MessengerViewModel(shellViewModel, account);


I use this factory class in my shell-view-model. Shell-view-model class look like this:

///<summary>/// Shell model interface///</summary>publicinterface IShellViewModel
  //create start up view-modelvoid ShowLogOnView();

  //this method create new view model//it is used in LogOnViewModelvoid ShowMessengerView(PokecAccount account);

 publicclass ShellViewModel : Conductor<IScreen>, IShellViewModel
  //factory interfaceprivatereadonly IViewModelFactory _factory;

  public ShellViewModel(IViewModelFactory factory)
   //inject factory
   _factory = factory;

   //show startup view model

  publicvoid ShowLogOnView()
   //create LogOnViewModel class with factoryvar model = _factory.CreateLogOnViewModel(this);


  ///<summary>/// Create MessengerViewModel///</summary>///<param name="account">account in this case is send from LogOnViewModel class </param>publicvoid ShowMessengerView(PokecAccount account)
   //create MessengerViewModel class with factoryvar model = _factory.CreateMessengerViewModel(this, account);



Start up view-model. LogOnViewModel class:

publicinterface ILogOnViewModel : IScreen, IDataErrorInfo
 string Nick { get; set; }
 string Password { get; set; }
 bool CanLogOn { get; set; }
 void LogOn(string nick, string password);

publicclass LogOnViewModel : Screen, ILogOnViewModel
 ///<summary>/// inject class from external assembly/// after creation of this class is still null///</summary>
 public IPokecConnection PokecConn { get; set; }

 privatereadonly IShellViewModel _shellViewModel = null;

 private PokecAccount _account = null;

 public LogOnViewModel(IShellViewModel shellViewModel)
  _shellViewModel = shellViewModel;
  _account = new PokecAccount();

 //CREATE NEW VIEW MODELpublicvoid CreateNewView()
  //create new view-model (MessengerViewModel)


MessengerViewModel class:

publicinterface IMessengerViewModel : IScreen
 BitmapImage AvatarImage { get; set; }
 string AvatarStatus { get; set; }
 KeyValuePair<string, Friend> SelectedFriend { get; set; }

publicclass MessengerViewModel : Screen, IMessengerViewModel

 private IPokecService _pokecService;
 private IPokecConnection _pokecConn;
 private IShellViewModel _shellViewModel = null;
 private PokecAccount _account = null;

 public MessengerViewModel(IShellViewModel shellViewModel, PokecAccount account)
  _shellViewModel = shellViewModel;
  _account = account;

I have problem with injection into view-model class. On creation of view-model classes I use factory pattern, but I need inject in this class also from external assembly.

For example: After creation of LogOnVieModel class is   IPokecConnection PokecConn{ get; set;} still null.

What is the most suitable solution in my case? Where is it problem ? Thank for help.

I have been asked a ques that Can we prevent SQL Injection using any Interface?  And the otions were like IdbParameters, IDataReader 2 more ...don't remember.
Please tell?

Hi All: I experienced what looks like a sql-injection attack on a webserver with a sql2005 back end. I know approximately when it happened (within 24 hours), but I can't find the request in the webserver logs...I don't know if the request was escaped or obfuscated in some way.

The dB is in a transaction-log shipping configuration, so I have .TRNs going back a couple of days that I could use to identify the exact query and time that it occurred, but I don't know if it's even possible to examine the TRNs this way?

Is there any way to examine the SQL transaction logs directly for the attack?

Don't ever use string concatenation (or a StringBuilder) to create SQL commands. An example is this:
string sql = "SELECT * FROM Products WHERE Category=" + cat;

There are a lot of reasons why not to do this:
1. Strings inside the command text needs to be enclosed between ' and '. You can have a problem when the value of cat contains a ' itself. You can avoid this by doubling all single quotes inside the cat string, but it still is not recommended.
2. SQL Injection attacks!!! Don't be tricked by this one, it's easy to avoid. Think of a string cat that contains the following value:
1; DROP TABLE Products; --

-- is the comment operator in T-SQL. So, the resulting command is this:
SELECT * FROM Products WHERE Category=1; DROP TABLE Products; --

The result: the Products table is droppe. Thus, pretty simple to do if the cat value comes from the querystring or from a form input.

How to avoid this:
1. Don't ever ever connect to the database as "sa" or another db owner with full access to the underlying database. Always connect with the least privileges needed to do the job.
2. Don't use string concat, but use parameterized commands instead, like this:
string query = "SELECT * FROM Products WHERE Category=@Category";

SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("@Category", SqlDbType.NVarChar, 50);
cmd.Parameters["@Category"].Value = cat;

This will make sure the anomalities with quotes are solved for you, as well as avoid basic injections and perform checkings for the input length of the strings (+ type checking etc).
3. Even better, use a stored procedure with parameters on the server and call it using SqlCommand. The idea is the same, but the SQL command with params itself is stored on the server. This allows better performance and even better security.

In a recent thread Erland Sommarskog has pointed out that even nchar(10) text input is big enough for an SQL injection attack. Demo follows:

/************* WARNING ****************
***************************************/USE tempdb;
/**** DISCLAIMER - DEMO CODE ONLY - DON'T USE IT PRODUCTION ****/CREATEPROC sprocSQLInjectionAttackDemo @input nchar(10)
   SET @SQL = ' SELECT Color FROM AdventureWorks2008.Production.Product'+CHAR(10)+
        ' WHERE Color like '+@input
   EXEC (@SQL)
-- Test SQL injection stored procedureDECLARE @input nchar(10)= '''''SHUTDOWN'EXEC sprocSQLInjectionAttackDemo @input
 SELECT Color FROM AdventureWorks2008.Production.Product
 WHERE Color like ''SHUTDOWN

(0 row(s) affected)
The SHUTDOWN statement cannot be executed within a transaction or by a 
stored procedure.
Msg 0, Level 11, State 0, Line 0
A severe error occurred on the current command. The results, if any, 
should be discarded.

Do you have an SQL Injection surprise story/script? If script, just cripple it to make it harmless.




I'm using a List Box to get multiple values that will be used in a query.

I can loop over the List Box and create the string.
i.e. 'blue','red','purple'

The string is used in the query: SELECT * FROM TABLE1 WHERE COLOR IN('blue','red','purple'). Is there a way to parametrize multiple values? @COLOR='blue','red','purple'

What will be the best practice to prevent SQL injections in this scenario?


Hi All,

I am struggling with the problem since the last week. The apllication is built upon the follwing technologies - ASP.NET 1.1, SQL SERVER 2005, extensive use of JavaScript.

I saw last week that an unknown script was aapended to one or more columns of every row in some sertain tables. I removed that script but it re-appeared once again. The script looks something like this (PLEASE DO NOT CLICK ON THIS LINK....I DON'T KNOW WHAT IT WILL DO)</title><script src="http://google-stats50 . info /ur. php>".

When the script reappeared, it may appear with different link (PLEASE DO NOT CLICK ON LINKS BELOW)

1) </title><script src="http:// google-stats49 . info /ur. php>"

2) </title><script src="http:// google-stats48 . info /ur. php>"

3) </title><script src="http:// google-stats47 . info /ur. php>"

4) </title><a style=display:none; href=http:// worid - of - books . com >book</a>

To prevent these scripts to re-appear, I took the following steps:

a) Encrypting the sensitive information in the Web.config file

b) Making the IFRAME element secure by applying the attribute security="restricted"

c) setting the character encoding in the Web.config file to ISO-8859-1:

After taking aforementioned steps, the scripts didn't  appear for around 24 hours. But It again came up.

Now what should I do? Please help.

Thanks in advance.


I want to know how to avoid sql injection in asp.net webforms??

if something is there like (select empid from emp where empid=textbox1.text) here the attacker can easily attack on the database,then how to write this same code to maintain security should we use query strings?? help me with this,thanks.


I want to know how to avoid sql injection in asp.net webforms??

if something is there like (select empid from emp where empid=textbox1.text) here the attacker can easily attack on the database,then how to write this same code to maintain security should we use query strings or parameters if so how?? help me with this,thanks.

 Guys there is a question in my mind

 please solve if u can.

 If someone hacks my online database from sql injection(After querying from any text box which is supplied on any page of my website for registration purpose or anything else).

So Can i tress his/her ip address that from where query was supplied.

Thanks a ton.

On my test system I've tried intentionally forming bad queries, but I'm either bad at it or GenericInvoker is safe from sql injection. I can't find any documentation supporting this, though. Is it my job to prevent SQL injection when using SharePoint's GenericInvoker, or is that already handled for me? It seems to be the latter, although again, I've seen no documentation supporting this. Thanks for any comments.

hi folks:
i want to use unity to do these below
i have a data access:
public class UtilesTableRepository:RepositoryBase
                public UtilesTableRepository(string warehouseNumber)
            //use warehouseNumber to init database controller:
 the parameter warehouseNumber'value only can get from another class's method, how can i use unity resolve the UtilesTableRepository, and automatic invoke the get warehouseNumber method and then pass the result to the constuctor?



Has anyone applied Policy Injection  (Enterprise Library 4.1) on a svcutil generated proxy class. I am having difficulty doing this as Unity is unable to reolve the base.Channel class to the concrete type as base.Channel itself is a Transparent Proxy class.




Hey everyone,

I am computer science student and am researching on Code injection and regular expressions.

If someone could help me to look at right direction on how to get general idea of real world applications using the Code Inj. and RegEx would be piece of gold for me.

Thank you in advance.
If I have a collection, an IList, which contains types that are also interfaces (e.g. IList<IMyTypes>). How would I use Unity to register and resolve something like this?

<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure