本实验报告详细探讨了利用ADO技术连接与操作SQL Server数据库的方法,并通过具体示例展示了如何高效地进行数据查询、更新和维护。
1. 主界面
2. 查询功能
当用户点击查询按钮时执行以下代码:
```csharp
private void chaxun_Click(object sender, System.EventArgs e)
{
// 创建SQL连接对象,指定数据库名称为李梦然07060021
SqlConnection thisConnection = new SqlConnection(Data Source=LocalHost;Integrated Security=SSPI;Initial Catalog=李梦然07060021);
// 定义查询语句
SqlCommand thisCommand = new SqlCommand(select * from student where sno= + textBox1.Text, thisConnection);
SqlDataAdapter thisAdapter = new SqlDataAdapter();
thisAdapter.SelectCommand = thisCommand;
DataSet thisDataSet = new DataSet();
// 打开数据库连接并填充数据集
thisConnection.Open();
thisAdapter.Fill(thisDataSet, student);
// 设置DataGrid的数据源和成员属性,显示查询结果
dataGrid1.SetDataBinding(thisDataSet,student);
// 关闭数据库连接
thisConnection.Close();
}
```
3. 浏览功能
当用户点击浏览按钮时执行以下代码:
```csharp
private void liulan_Click(object sender, System.EventArgs e)
{
SqlConnection thisConnection = new SqlConnection(Data Source=LocalHost;Integrated Security=SSPI;Initial Catalog=李梦然07060021);
SqlDataAdapter thisAdapter = new SqlDataAdapter();
DataSet thisDataSet = new DataSet();
// 创建SQL命令对象
SqlCommand thisCommand=thisConnection.CreateCommand();
thisCommand.CommandText=select * from student;
// 设置适配器的SelectCommand属性为SqlCommand对象
thisAdapter.SelectCommand =thisCommand;
// 打开数据库连接并填充数据集
thisConnection.Open();
thisAdapter.Fill(thisDataSet,student);
// 关闭数据库连接
thisConnection.Close();
dataGrid1.SetDataBinding(thisDataSet, student);
}
```
4. 插入新列
当用户点击按钮时执行以下代码:
```csharp
private void button1_Click(object sender, System.EventArgs e)
{
SqlConnection thisConnection = new SqlConnection(Data Source=LocalHost;Integrated Security=SSPI;Initial Catalog=李梦然07060021);
SqlDataAdapter thisAdapter = new SqlDataAdapter();
DataSet thisDataSet = new DataSet();
// 创建SQL命令对象
SqlCommand thisCommand=thisConnection.CreateCommand();
thisCommand.CommandText=select * from student;
// 设置适配器的SelectCommand属性为SqlCommand对象
thisAdapter.SelectCommand= thisCommand;
// 打开数据库连接并填充数据集
thisConnection.Open();
// 创建SQL命令生成器,用于处理更新操作
SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
// 填充数据集
thisAdapter.Fill(thisDataSet, student);
// 在数据集中创建新行,并设置其字段值
DataRow newRow =thisDataSet.Tables[student].NewRow();
newRow [sno]=21;
newRow [sname]=李梦然;
newRow [ssex]=男;
newRow [thirthday]=1987-7-31;
newRow [class]=95001;
// 将新行添加到数据集中
thisDataSet.Tables[student].Rows.Add(newRow);
// 更新数据库中的表
thisAdapter.Update(thisDataSet,student);
// 显示更新后的表格信息
thisCommand.CommandText=select * from student;
dataGrid1.SetDataBinding(thisDataSet, student);
// 关闭数据库连接
thisConnection.Close();
}
```