SELECT Max(*) as mymax FROM score where subject='" + comboBox1.Text + "'", mycon
SELECT Min(*) as mymin FROM score where subject='" + comboBox1.Text + "'", mycon
SELECT Avg(*) as myavg FROM score where subject='" + comboBox1.Text + "'", mycon
SELECT Count(*) as mycount FROM score where subject='" + comboBox1.Text + "' and score>60", mycon
写成代码,求大佬!!!
好的,我来回答你的问题:
如果使用 C#,可以将 SQL 语句写成字符串,再使用 SqlCommand 类执行查询,例如:
string subject = comboBox1.Text;
string sql = "SELECT Max(*) as mymax FROM score where subject=@subject";
SqlCommand command = new SqlCommand(sql, mycon);
command.Parameters.AddWithValue("@subject", subject);
int maxScore = (int) command.ExecuteScalar();
其中,使用 @subject 作为参数名,可以避免 SQL 注入攻击;ExecuteScalar() 方法可以返回查询结果中的第一行和第一列,即最大分数。
同样地,最小分数、平均分数、及格人数也可以用类似的方法查询,代码如下:
// 最小分数
string sql = "SELECT Min(*) as mymin FROM score where subject=@subject";
SqlCommand command = new SqlCommand(sql, mycon);
command.Parameters.AddWithValue("@subject", subject);
int minScore = (int) command.ExecuteScalar();
// 平均分数
string sql = "SELECT Avg(*) as myavg FROM score where subject=@subject";
SqlCommand command = new SqlCommand(sql, mycon);
command.Parameters.AddWithValue("@subject", subject);
double avgScore = (double) command.ExecuteScalar();
// 及格人数
string sql = "SELECT Count(*) as mycount FROM score where subject=@subject and score>60";
SqlCommand command = new SqlCommand(sql, mycon);
command.Parameters.AddWithValue("@subject", subject);
int passCount = (int) command.ExecuteScalar();