DataAdapter批量插入数据
using (Conn = new SqlConnection(ConnectionString))
{
Conn.Open();//打开数据库连接
string sqlstr = "select * from UserInfo2";
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand insertcmd = new SqlCommand(sqlstr, Conn);//创建Command实例
SqlCommandBuilder cb = new SqlCommandBuilder(da);//自动生成插入数据的SQL语句,不能少
da.SelectCommand = insertcmd;//必须设置此项
DataSet ds = new DataSet();
int count = da.Fill(ds, "UserInfo2");//填充DataSet
if (count > 0)
{
//添加第一行数据
DataRow dr = ds.Tables["UserInfo2"].NewRow();//添加新行
dr["UserName"] = "小赵";
dr["Pwd"] = "123";
ds.Tables["UserInfo2"].Rows.Add(dr);//此句不能少
//添加第二行数据
dr = ds.Tables["UserInfo2"].NewRow();//继续添加新行
dr["UserName"] = "小张";
dr["Pwd"] = "111";
ds.Tables["UserInfo2"].Rows.Add(dr);
da.Update(ds, "UserInfo2");//更新数据库
}
ds.Clear();
Response.Write("批量添加数据成功!");
}
DataAdapter批量更新数据
using (Conn = new SqlConnection(ConnectionString))
{
//DataAdapter批量更新数据
Conn.Open();//打开数据库连接
string sqlstr = "select * from UserInfo2";
SqlDataAdapter da = new SqlDataAdapter();//创建DataAdapter实例
SqlCommand updatecmd = new SqlCommand(sqlstr, Conn);//创建Command实例
SqlCommandBuilder cb = new SqlCommandBuilder(da);//自动生成插入数据的SQL语句,不能少
da.SelectCommand = updatecmd;
DataSet ds = new DataSet();
int count = da.Fill(ds, "UserInfo2");
if (count > 0)
{
for (int i = 1; i < count; i++)
{
ds.Tables["UserInfo2"].Rows[i]["Pwd"] = "111";//修改列值
}
da.Update(ds, "UserInfo2");//将DataSet中的数据更新到数据库
}
ds.Clear();
Response.Write("批量更新数据成功!");
}
DataAdapter批量删除数据
using (Conn = new SqlConnection(ConnectionString))
{
Conn.Open();//打开数据库连接
string sqlstr = "select * from UserInfo2";
SqlDataAdapter da = new SqlDataAdapter();//创建DataAdapter实例
SqlCommand updatecmd = new SqlCommand(sqlstr, Conn);//创建Command实例
SqlCommandBuilder cb = new SqlCommandBuilder(da);//自动生成插入数据的SQL语句,不能少
da.SelectCommand = updatecmd;
DataSet ds = new DataSet();
int count = da.Fill(ds, "UserInfo2");
if (count > 0)
{
for (int i = 2; i < count; i++)
{
ds.Tables["UserInfo2"].Rows[i].Delete();//删除行数据
}
da.Update(ds, "UserInfo2");
}
ds.Clear();
Response.Write("批量删除数据成功!");
}