开发者

Sql query in c#

开发者 https://www.devze.com 2023-03-10 05:18 出处:网络
I am programming in C# 2010 Express. I have a SQL database in my program, one of its tables called HightAndWei开发者_开发百科ghtTable that has four columns. I want to select a value from the fourth c

I am programming in C# 2010 Express.

I have a SQL database in my program, one of its tables called HightAndWei开发者_开发百科ghtTable that has four columns. I want to select a value from the fourth column that is called Risk based on the height that the user enter in the domain in up down box.

Thus, my SQL query in the program is :

SELECT Risk 
FROM HightAndWeightTable 
WHERE Hight LIKE '%" + domainUpDown1.Text + "%'"

... but this didn't work.

Also, how do we write a SQL query that has a range, e.g. if I want to say a value is in between a range of values?


First off, one problem you're running into is SQL Injection. This has been written about many many many times, so I won't go too much into it here.

You want to change your SQL Query to use parameters, like so:

using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI")
{

    SqlCommand cmd = new SqlCommand("SELECT Risk From HightAndWeightTable WHERE Hight LIKE '%" + @height + "%'", conn);

    SqlParameter param = new SqlParameter();
    param.ParameterName = "@height";
    param.Value = domainUpDown1.Text;

    cmd.Parameters.Add(param);

    reader = cmd.ExecuteReader();

    while(reader.Read())
    {
        //do something here:
        string risk = reader["Risk"];
    }
}

Also, are you spelling everything correctly in your query? It looks like you misspelled height.

As far as between:

SELECT thing t FROM table where t.value BETWEEN lowerLimit AND upperLimit


First, you don't want to use LIKE when comparing what I assume are numeric values. You can just do = or > or whatever is appropriate for your comparison.

Second, please please please, tell me that you're either doing validation on that user input or you're not really planning on using string concatenation to build your SQL Strings (use parameters!)

Third, range can be accomplished using the BETWEEN operator.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号