繁体   English   中英

使用C#从SQL Server 2005中获取数据

[英]Fetching data from SQL Server 2005 using c#

当其他两个列的值相等时,我想从表中检索特定列。 我的代码如下。 四个列分别是id,destination,source,price

我想在目的地和来源相等时显示价格。

请你帮助我好吗?

private void button1_Click(object sender, EventArgs e)
{

        SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true");
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter();

        DataTable dt = new DataTable();
        da.SelectCommand = new SqlCommand("select  price from metro where source='" + textBox1.Text + "' and destination='" + textBox2.Text + "'", con);
        da.Fill(dt);
        for(int i=0;i<dt.Rows.Count;i++)
        {
            textBox3.Text = dt.Rows[0][3].Count.ToString();
        }
    }

我想你在这之后....

    private void button1_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true"))
        {
            string query = "select  price from metro where source= @Source and destination = @Destination";

            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.AddWithValue("@Source", textBox1.Text);
                cmd.Parameters.AddWithValue("@Destination", textBox2.Text);

                con.Open();
                object o  = cmd.ExecuteScalar();
                if(o != null && o != DBNull.Value)
                {
                   string price = (string) o; //please cast the return type as required
                   textBox3.Text = price;
                }
                con.Close();
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM