/// <summary>
/// 更新DataSet
/// </summary>
/// <param name="cnnStr">连接串</param>
/// <param name="ds">要更新的DataSet</param>
/// <param name="sqlBefore">在更新之前执行的SQL</param>
/// <param name="sqlAfter">在更新之后执行的SQL</param>
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();
}
}
/// <summary>
/// 更新DataSet
/// </summary>
/// <param name="cnnStr"></param>
/// <param name="tableName"></param>
/// <param name="ds"></param>
public static void Update(string connectionString, DataSet ds)
{
Update(connectionString, ds, string.Empty, string.Empty);
}
为什么我执行的结果是全部是新增而不是修改?
不明白你想要的效果。