dataset如何批量更新添加数据库
发布网友
发布时间:2022-04-08 01:16
我来回答
共1个回答
热心网友
时间:2022-04-08 02:46
dataset如何批量更新添加数据库
/
///
更新DataSet
///
///
///
///
///
public
static
void
Update(string
connectionString,
DataSet
ds,
string
sqlBefore,
string
sqlAfter)
{
SqlDataAdapter
da
=
null;
SqlTransaction
tran
=
null;
using(SqlConnection
cnn
=
new
SqlConnection(connectionString))
{
cnn.Open();
tran
=
cnn.BeginTransaction();
if(!string.IsNullOrEmpty(sqlBefore.Trim()))
//执行更新前的SQL
{
using(SqlCommand
cmd
=
new
SqlCommand(sqlBefore.Trim(),
cnn,
tran))
{
cmd.ExecuteNonQuery();
}
}
foreach(DataTable
dt
in
ds.Tables)
{
string
sql
=
string.Format("SELECT
*
FROM
{0}
WHERE
1
=
0
",
dt.TableName);
if(dt.ExtendedProperties["SELECT"]
!=
null)
{
sql
=
dt.ExtendedProperties["SELECT"].ToString();
}
da
=
new
SqlDataAdapter();
SqlCommandBuilder
cb
=
new
SqlCommandBuilder(da);
da.SelectCommand
=
new
SqlCommand(sql,
cnn,
tran);
da.Update(ds,
dt.TableName);
}
if(!string.IsNullOrEmpty(sqlAfter.Trim()))
//执行更新后的SQL
{
using(SqlCommand
cmd
=
new
SqlCommand(sqlAfter.Trim(),
cnn,
tran))
{
cmd.ExecuteNonQuery();
}
}
tran.Commit();
}
}
///
///
更新DataSet
///
///
///
///
public
static
void
Update(string
connectionString,
DataSet
ds)
{
Update(connectionString,
ds,
string.Empty,
string.Empty);
}