从标签上的SQL Server打印我的搜索结果

时间:2015-12-24 08:06:19

标签: c# sql-server

我只是想在表格上打印标签上的搜索总和。

故事是我有2个文本框,它会给我2个日期并在我的数据库中搜索,并在该2日期之间打印总和成本的答案。

我的代码是:

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=SuperCalc;Integrated Security=True");

    SqlCommand com = new SqlCommand();

    if (con.State == ConnectionState.Closed)
    {
        con.Open();

        com = new SqlCommand("select sum (Cost) as JameKol From TBL_Cost Where CostDate between '" + textBox1.Text + "' and '" + textBox2.Text + "' ", con);
        label5.Text = com();

        con.Close();
        MessageBox.Show("Search is done", "Done");
    }
}

com不能用作方法,所以,我该怎么做?

1 个答案:

答案 0 :(得分:3)

只需使用ExecuteScalar就是这个。它获得第一行的第一列,符合SUM函数。

label5.Text = com.ExecuteScalar().ToString();

但更重要的是,您应该始终使用parameterized queries。这种字符串连接对SQL Injection攻击是开放的。

使用using statement自动处理您的连接和命令,而不是手动调用Close方法。

顺便说一句,看起来您的CostDate列是字符类型。不要这样做。 This is a bad habit to kick。您应永远DateTime值保留为字符。将其更改为datetime或更好datetime2类型,并将您的DateTime直接传递给参数化查询。这就是我使用DateTime.Parse来解析您的Text值的原因。如果无法解析它们,您也可以使用ParseExact

string conString = "Data Source=localhost;Initial Catalog=SuperCalc;Integrated Security=True";
using(var con = new SqlConnection(conString))
using(var com = con.CreateCommand())
{
    com.CommandText = @"select sum (Cost) as JameKol From TBL_Cost 
                        Where CostDate between @date1 and @date2";
    com.Parameters.Add("@date1", SqlDbType.DateTime2).Value = DateTime.Parse(textBox1.Text);
    com.Parameters.Add("@date2", SqlDbType.DateTime2).Value = DateTime.Parse(textBox2.Text);
    con.Open();
    label5.Text = com.ExecuteScalar().ToString();
}