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
No comments:
Post a Comment