使用DataTable更新数据库(增,删,改)
编程学习 2021-07-04 22:40www.dzhlxh.cn编程入门
使用DataTable更新数据库(增,删,改),需要的朋友可以参考一下
1、修改数据
DataRow dr = hRDataSet.Tables["emp"].Rows.Find(textBox3.Text);
//DataRow dr = hRDataSet.Tables["emp"].Select("id="+textBox3.Text)[0];
dr.BeginEdit();
dr["name"] = textBox1.Text;
dr.EndEdit();
SqlCommandBuilder cmd=new SqlCommandBuilder(empTableAdapter);
empTableAdapter.Update(hRDataSet);
this.empTableAdapter.Fill(this.hRDataSet.emp);
2、插入数据
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
{
String sql = "select id,name,age from emp";
SqlDataAdapter adp = new SqlDataAdapter(sql, conn);
adp.Fill(ds);
DataRow dr=ds.Tables[0].NewRow();
dr["name"]=txtName.Text;
dr["age"] = Convert.ToInt32(txtAge.Text);
SqlCommandBuilder cmd=new SqlCommandBuilder(adp);
ds.Tables[0].Rows.Add(dr);
adp.Update(ds);
}
3、删除数据
DataRow dr = hRDataSet.Tables["emp"].Rows.Find(textBox3.Text);
//DataRow dr = hRDataSet.Tables["emp"].Select("id="+textBox3.Text)[0];
dr.Delete();
SqlCommandBuilder cmd=new SqlCommandBuilder(empTableAdapter);
empTableAdapter.Update(hRDataSet);
this.empTableAdapter.Fill(this.hRDataSet.emp);
代码如下:
DataRow dr = hRDataSet.Tables["emp"].Rows.Find(textBox3.Text);
//DataRow dr = hRDataSet.Tables["emp"].Select("id="+textBox3.Text)[0];
dr.BeginEdit();
dr["name"] = textBox1.Text;
dr.EndEdit();
SqlCommandBuilder cmd=new SqlCommandBuilder(empTableAdapter);
empTableAdapter.Update(hRDataSet);
this.empTableAdapter.Fill(this.hRDataSet.emp);
2、插入数据
代码如下:
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
{
String sql = "select id,name,age from emp";
SqlDataAdapter adp = new SqlDataAdapter(sql, conn);
adp.Fill(ds);
DataRow dr=ds.Tables[0].NewRow();
dr["name"]=txtName.Text;
dr["age"] = Convert.ToInt32(txtAge.Text);
SqlCommandBuilder cmd=new SqlCommandBuilder(adp);
ds.Tables[0].Rows.Add(dr);
adp.Update(ds);
}
3、删除数据
代码如下:
DataRow dr = hRDataSet.Tables["emp"].Rows.Find(textBox3.Text);
//DataRow dr = hRDataSet.Tables["emp"].Select("id="+textBox3.Text)[0];
dr.Delete();
SqlCommandBuilder cmd=new SqlCommandBuilder(empTableAdapter);
empTableAdapter.Update(hRDataSet);
this.empTableAdapter.Fill(this.hRDataSet.emp);