Click here to Skip to main content
16,016,736 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Select query is not working when i'm trying to check 3 conditions together in where clause...The code is as follows

C#
protected void Page_Load(object sender, EventArgs e)
{
   GetResults();
}

private void GetResults()
{
   SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HousingConnectionString"].ConnectionString);
   conn.Open();
   string query;
   SqlCommand com;
   SqlDataReader reader;

   SqlDataAdapter adapter = new SqlDataAdapter();

   query = "SELECT Flat, First_Name, Middle_Name, Last_Name, Mobile_No, Email, DOB, Age, Education, Office_Add, Native_Add, PAN_Card, Aadhar_Card, Religion, Business_Job, Married_Unmarried, No_Of_Members, Joining_Date from Primary_Member where Flat='" + Request.QueryString["fnum"] + "'";

   com = new SqlCommand(query, conn);
   adapter.SelectCommand = new SqlCommand(query, conn);
   reader = com.ExecuteReader();
   GridView1.DataSource = reader;
   GridView1.DataBind();
}
Posted
Updated 22-Oct-15 5:13am
v2
Comments
F-ES Sitecore 22-Oct-15 11:20am    
What does Request.QueryString["fnum"] return? If you want multiple selections to be possible you'll need to use "in" and you'll need to format it correctly

where Flat in ('oprion 1', 'option 2', 'option 3')

Also your code is liable to sql injection attacks.

1 solution

1. This is a dangerous way to code. It's exposed to sql injection. Please use parameters instead of concatenating code. For example:
C#
query = "SELECT ... FROM ... WHERE Flat = @Flat";
...
com.Parameters.AddWithValue("@Flat", Request.QueryString["fnum"]);


2. You are only passing in 1 condition in your WHERE clause but you said you had a problem with 3.

3. Write your query in Sql Management Studio first and get it working there. Then you can easily put it into C#.

4. I would also recommend instead of using the inline sql that you write a stored procedure and call it instead.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900