使用DataSet和存储过程更新数据库
在数据库中创建一个名为Semployee的存储过程
CREATE PROCEDURE Semployee
(
@name nvarchar(50),
@date datetime,
@PartmentId int
)
AS
insert into T_employee(E_name,E_date,E_PartmentId) values(@name,@date,@PartmentId)
DataSet先获取数据,定义一个更新函数,代码如下
{
DataAccess da = new DataAccess();
string str = "select * from T_employee";
DataSet ds = da.GetDs(str,"T_employee"); //定义一个DataSet并获取了数据集
DataRow dr = ds.Tables[0].NewRow(); //创建一个DataRow对象 ,通过newRow()实例
dr["E_name"] = TextBox1.Text;
dr["E_date"] = DateTime.Now.ToString();
dr["E_PartmentId"] = TextBox3.Text;
ds.Tables[0].Rows.Add(dr); //为DataSet中的数据集添加数据
UpdateStore(ds); //执行更新操作
}
public void UpdateStore(DataSet ds)
{ DataAccess da=new DataAccess();
SqlConnection cn=da.conn;
SqlCommand cmd = new SqlCommand("Semployee",cn);
cmd.Parameters.Add("@name",SqlDbType.NVarChar,50,"E_name"); //@name与存储过程中的@name参数相对应,"E_name"与DataSet中的数据集字段名相对应,即和数据库表中的字段名相对应
cmd.Parameters.Add("@date",SqlDbType.DateTime,8,"E_date");
cmd.Parameters.Add("@PartmentID",SqlDbType.Int,4,"E_PartmentId");
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter();
sda.InsertCommand = cmd;
cn.Open();
sda.Update(ds,"T_employee"); //将DataSet中数据集的数据更新到数据库表中
cn.Close();
}

浙公网安备 33010602011771号