如何通过两个字段选择一个记录 [英] how to select one record by two field

查看:101
本文介绍了如何通过两个字段选择一个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的朋友。

1.我有3个字段:1。2年3.月3.价格

2.我有两个TextBox年份和价格选择一个月的DropDownList

3.now我想通过从DropDownList和year中选择值来选择或搜索一条且只有一条记录,并希望在GridView中显示

现在我的问题是我不知道如何为此设置查询

这是我的代码不起作用:





Hi my Friends.
1.I have 3 fields : 1. year 2. month 3.price
2.I have two TextBox for year and price and a DropDownList for select a month
3.now I want to select or search a one and only one record by selecting value from DropDownList and year and want to show in GridView
now my problem is that I don't know how to set query for this
this is my code that don't work:


protected void Button5_Click(object sender, EventArgs e)
    {
        String cstr = @"Data Source=FAZI-PC\REZA_FAZI;Initial Catalog=ejra_db;Integrated Security=True";
        SqlConnection scon = new SqlConnection(cstr);
        connection.Open();
        String searchstr = String.Format("SELECT * From shakhes WHERE year,month={0}'{1}'",
                                           TextBox3.Text,DropDownList1.SelectedIndex);
                                      
        SqlCommand searchcmd = new SqlCommand(searchstr,scon);
        SqlDataReader dr = searchcmd.ExecuteReader();

        if (dr.HasRows)
        {
            dr.Read();
            TextBox4.Text=dr["price"].ToString();
            int ddl = Int32.Parse(dr["month"].ToString());
            DropDownList1.SelectedIndex = ddl;
        }
        else 
        {
            Label6.ForeColor = Color.Red;
            Label6.Text = "there is no data";
        }
        dr.Close() ;
        connection.Close();
    }







请帮帮我




please help me

推荐答案

对于初学者,不要这样做!

连接字符串从SQL命令获取是对SQL注入的邀请,可能会损坏或破坏您的数据库。

尝试:



For starters, don't do it like that!
Concatenating strings took form an SQL command is an invitation to SQL Injection, which can damage or destroy your database.
Try:

string searchstr = string.Format("SELECT * From shakhes WHERE year = @YR AND month=@MN";
SqlCommand cmd = new SqlCommand(searchstr,scon);
cmd.Parameters.AddWithValue("@YR",x3.Text);
cmd.Parameters.AddWithValue("@MN",DropDownList1.SelectedIndex);

结果将取决于您的查询。

如果返回相同的记录,您可以使用 DISTINCT 关键字。

如果您只想要最高记录,请使用 TOP keyword。



最后但并非最不重要的是过滤您对主键的查询,以便获得单条记录。

Of当然,除非是用户定义的字段,否则您的用户不会知道主键。
The result will depend on your query.
If the same record is returned you could use the DISTINCT keyword.
If you just want the top most record use TOP keyword.

Last but not least filter your query on the primary key so you get a single record.
Of course, your user would not know the primary key unless it is a user defined field.


这篇关于如何通过两个字段选择一个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆