簡體   English   中英

如何在ASP.NET C#中使用SQL查詢獲取數字總和?

[英]How to get sum of numbers using SQL query in ASP.NET C#?

我是ASP.NET Web開發的初學者。現在,我想使用SQL和查詢來查找標記和。 但是執行查詢后發現-1為總和。 這是我的代碼:

public double GetTotalScore(string regNo)
{
    SqlConnection connection=new SqlConnection(ConnectionString);
    string query = "select sum(Score) from SaveResult where RegNo='" + regNo + "' group by RegNo";
    SqlCommand command = new SqlCommand(query, connection);
    connection.Open();
    double total = command.ExecuteNonQuery();
    connection.Close();
    return total;
} 

如何使用sql查詢獲取總和?

ExecuteNonQuery返回受影響的行數。

ExecuteScalar是您想要的方法。 它向您返回一個單值(“標量”)。

public double GetTotalScore(string regNo)
    {
        SqlConnection connection=new SqlConnection(ConnectionString);

        string query = "select sum(Score) from SaveResult where RegNo='" + regNo + "' group by RegNo";
        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();
        double total =  (double)cmd.ExecuteScalar();
        connection.Close();
        return total;
    } 

你還是有問題

   string query = "select sum(Score) from SaveResult where RegNo='" + regNo + "' group by RegNo";

您需要更改為參數化查詢。

   string query = "select sum(Score) from SaveResult where RegNo='@MyParameter' group by RegNo";


        SqlParameter param  = new SqlParameter();
        param.ParameterName = "@MyParameter";
        param.Value         = "myvalue";


        cmd.Parameters.Add(param);

/ *現在調用ExecuteScalar * /

看到

http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06

public string GetTotalScore(string regNo)
    {
        SqlConnection connection=new SqlConnection(ConnectionString);
        string query = "select sum(Score) from SaveResult where RegNo='"+regNo+"' group by RegNo";
        SqlCommand command = new SqlCommand(query, connection);  
        connection.Open();
        object total = command.ExecuteScalar();
        connection.Close();
        return Convert.ToString(total);
    }    
}

它可以使用ExecuteScalar求和。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM