1. 使用保持连接的方式编写程序,计算各年级平均成绩,并显示结果。
【解答】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 习题8_6_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//添加Button按钮在ListBox中显示结果
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add("年级 平均成绩");
string connectionString = Properties.Settings.Default.MyDatabaseConnectionString;
//根据连接字符串创建SqlConnection实例
SqlConnection conn = new SqlConnection(connectionString);
//创建SqlCommand实例,并设置SQL语句和使用的连接实例
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select substring(学号,1,2) as 年级,avg(成绩) as 平均成绩 from MyTable2 group by substring(学号,1,2)";
cmd.Connection = conn;
try
{
conn.Open();
SqlDataReader r = cmd.ExecuteReader();
while (r.Read() == true)
{
listBox1.Items.Add(string.Format("{0}级 {1}", r[0], r[1]));
}
r.Close();
}
catch (Exception err)
{
MessageBox.Show(err.Message, "计算成绩失败");
}
finally
{
conn.Close();
}
}
}
}
2. 使用保持连接的方式编写程序,查询MyTable2中不及格学生的学号,姓名,性别,成绩。并将结果在ListBox中显示出来。
【解答】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 习题8_6_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(" 学号 姓名 性别 成绩");
string connectionString = Properties.Settings.Default.MyDatabaseConnectionString;
//根据连接字符串创建SqlConnection实例
SqlConnection conn = new SqlConnection(connectionString);
//创建SqlCommand实例,并设置SQL语句和使用的连接实例
SqlCommand cmd = new SqlCommand();
cmd.CommandText =
"Select 学号,姓名,性别, 成绩 From MyTable2 Where (成绩<60)";
cmd.Connection = conn;
try
{
conn.Open();
SqlDataReader r = cmd.ExecuteReader();
while (r.Read() == true)
{
listBox1.Items.Add( string.Format("{0} {1} {2} {3}", r[0], r[1], r[2], r[3]));
}
r.Close();
}
catch (Exception err)
{
MessageBox.Show(err.Message, "查询成绩失败");
}
finally
{
conn.Close();
}
}
}
}
3. 编写程序,以“[编码]名称”的样式在comboBox1中显示MyTable1的内容。
【解答】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 习题8_6_3
{
public partial class&n