private void LoadStudentInfo()//加载数据到DataSet
{
//5.实例化conn
conn = new SqlConnection(connString);
//6.使用键值对的方法 对表进行赋值 并查询
Dictionary<string, string> dic = new Dictionary<string, string>();
//7.定义查询语句
string sql = “SELECT*FROM Student”;
//8.向泛型集合中添加键值对
dic.Add(“Student”, sql);
//9.循环遍历集合
foreach (KeyValuePair<string, string> item in dic)
{
//10.实例化cmd
SqlCommand cmd = new SqlCommand(item.Value, conn);
//11实例化DataAdapter
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//12定义DataAdapter的类型
sda.SelectCommand = cmd;
//13.打开conn
conn.Open();
//填充数据到DataSet中
sda.Fill(ds, item.Key);
//添加主键
ds.Tables["Student"].PrimaryKey = new DataColumn[] { ds.Tables["Student"].Columns["SNO"] };
//15.关闭conn
conn.Close();
}
//展示数据到DataGV控件
dgvStudent.DataSource = null;
dgvStudent.DataSource = ds.Tables["Student"];
}
//添加
private void AddStudentInfo()//添加数据
{
//定义查询语句
string sql = "INSERT INTO Student(SNO,SName) values({0},'{1}')";
sql = string.Format(sql, txtSelectSNO.Text, txtSelectName.Text);
//实例化cmd
SqlCommand cmd = new SqlCommand(sql, conn);
//实例化dataAdapter
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//定义DataAdapter的类型
sda.InsertCommand = cmd;
//打开conn
conn.Open();
//执行
sda.Update(ds,"Student");
//关闭
conn.Close();
}
private void UpdataStudentInfo()//更改数据
{
//定义Sql语句
string sql = "UPDATE Student SET SName='{0}' Where SNO='{1}'";
sql = string.Format(sql, txtSelectName.Text, txtSelectSNO.Text);
//实例化cmd
SqlCommand cmd = new SqlCommand(sql, conn);
//实例化dataAdapter
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//定义DataAdapter的类型
sda.UpdateCommand = cmd;
//打开conn
conn.Open();
//执行更新
sda.Fill(ds, "Student");
//关闭conn
conn.Close();
}
private void DeleteStudentInfo()//删除数据
{
//定义SQL语句
string sql = "DELETE FROM Student WHERE SNO='{0}' ";
sql = string.Format(sql, IsName);
//实例化cmd
SqlCommand cmd = new SqlCommand(sql, conn);
//实例化dataAdapater
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//定义类型
sda.DeleteCommand = cmd;
//打开
conn.Open();
//执行
sda.Fill(ds, "Student");
//关闭
conn.Close();
}