我正在创建一个学生数据库,其中包含课程ID,课程名称,每门课程的学分,通过失败声明和成绩。现在我想在一个按钮中获得成绩的总和,并使它们出现在文本框中。这是我写的代码,但它给了我一个错误,说sum函数不存在。我该怎么办?
private void button1_Click(object sender, EventArgs e)
{
string ConString = " datasource = localhost; port = 3306; username = root; password = 3306";
string Query = " Select sum (grade) form studentdata.semestre1";
MySqlConnection ConDatabase = new MySqlConnection(ConString);
MySqlCommand cmdDataBase = new MySqlCommand(Query, ConDatabase);
MySqlDataReader myReader;
ConDatabase.Open();
myReader = cmdDataBase.ExecuteReader() ;
while (myReader.Read())
{
textBox2.Text = myReader.GetString(0);
}
myReader.Close();
答案 0 :(得分:2)
有两个原因:
SQL查询在函数和列名之间不应有空格
从"表单"更改您的查询到" FROM"
string Query = "Select SUM(grade) FROM studentdata.semestre1";
答案 1 :(得分:1)
尝试:
SELECT SUM(grade) FROM studentdata.semestre1
最重要的变化是from
。
要获得更完整的修复;添加using
,并在此处使用ExecuteScalar
:
using(MySqlConnection ConDatabase = new MySqlConnection(ConString))
using(MySqlCommand cmdDataBase = new MySqlCommand(
"SELECT SUM(grade) FROM studentdata.semestre1", ConDatabase))
{
ConDatabase.Open();
textBox2.Text = Convert.ToString(cmdDataBase.ExecuteScalar());
}