Windows Phone Developers

Friday, April 23, 2010

Parametrized Query in C# / .NET

How to pass parameters in SQL Queries in .NET (C#)

Parametrized queries are more secure (avoids SQL Injection etc) and easy to handle. The following example shows an simple example.


The above table has details of Players like name, contact details etc.

Let us try to get the details of players whose first name is 'Sachin'. First make a connection to database :

string sConString = GetConnectionString("TeamDBConnectionString");
            SqlConnection Con = new SqlConnection(sConString);
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Con;

            Con.Open();


Then set the CommandText property of SQLCommand and pass the parameters

String sSQLCmdText = "Select * from PlayerDetails where PlayerFirstName  = @FirstName";
            Cmd.CommandText = sSQLCmdText;
            Cmd.Parameters.AddWithValue("@FirstName", "Sachin");

Once this done, declare a SQLDataReader and get the rows into it


SqlDataReader rdr = Cmd.ExecuteReader();

            while (rdr.Read() == true)
            {
              string sPlayerName =  rdr.GetString(1);
            }
            
            Con.Close();


You can also pass the FieldName as parameter to query Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment