我无法从数据库中获取总和

I can't get the total sum from the database

我正在尝试从我的数据库中获取罚款总额并将其显示给我的 lblFine.Text,但他们总是出错:

System.Data.SqlClient.SqlException: 'Conversion failed when converting the varchar value 'Student ID' to data type int.'

这是我的代码:

public void CountFine()
{
    cn.Open();
    cm = new SqlCommand("SELECT SUM(totalFine) FROM tblFine where studentID = '" + lblStudID.Text + "'", cn);
    lblFine.Text = cm.ExecuteScalar().ToString();
    cn.Close();
}

如有任何帮助,我们将不胜感激

您的数据库中 studentID 的类型似乎是整数,因此您需要将 lblStudentId 的值转换为整数。然而,这种字符串连接对 SQL 注入攻击是开放的。您应该始终使用 parameterized queries to avoid SQL Injection 并消除错误:

cm = new SqlCommand("SELECT SUM(totalFine) FROM tblFine where studentID = @studentId", cn);
cm.Parameters.AddWithValue("@studentId", Convert.ToInt32(lblStudID.Text));

虽然直接指定类型并使用值 属性 比 AddWithValue::

更好
cm.Parameters.Add("@studentId", SqlDbType.Int).Value = Convert.ToInt32(lblStudID.Text);

在此处阅读更多内容:https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/