在 ADO.NET 中执行 SUM 查询

Perform SUM query in ADO.NET

我收到以下错误

;expected

我试图在我的 webform 中找到列值的总和。

protected void Page_Load(object sender, EventArgs e)
{
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "Select SUM("AMOUNT DEPOSITED ") From MAIN_TABLE6";
    Double amount = cmd.ExecuteScalar();
    Label3.Text = amount.ToString();
} 

使用括号将您在 SQL Server.

中的列括起来
protected void Page_Load(object sender, EventArgs e)
{
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "Select SUM([AMOUNT DEPOSITED]) From MAIN_TABLE6";
    Double amount = cmd.ExecuteScalar();
    Label3.Text = amount.ToString();    
} 

我更新了@ϻᴇᴛᴀʟ 的答案,因为他用括号解决了问题。但是我喜欢看到数据库对象被关闭和处置。如果数据库对象保留在使用它们的方法的本地,那么即使存在错误,using 块也会完成此操作。

可以将连接字符串直接传递给连接的构造函数,将命令文本和连接传递给命令的构造函数。 CommandType.Text为默认值,无需设置。

我在 .Execute... 之前直接打开了连接,之后立即关闭了。在连接关闭之前,用户界面不会更新。

    protected void Page_Load(object sender, EventArgs e)
    {
        double amount;
        using (SqlConnection con = new SqlConnection("Your connection string"))
        using (SqlCommand cmd = new SqlCommand("Select SUM([AMOUNT DEPOSITED]) From MAIN_TABLE6;", con))
        {
            con.Open();
            amount = (double)cmd.ExecuteScalar();
        }
        Label3.Text = amount.ToString();
    }