111,120
社区成员
发帖
与我相关
我的任务
分享
for (int i = 0; i < this.Rows.Count; i++)
{
DataRow r = this.Rows[i];
switch (r.RowState)
{
case DataRowState.Deleted:
if (PublicUpdateDataBaseEvents(r))
continue;
sql.Append(SQLBuilder.GetDeleteSql(r));
r.AcceptChanges();
i--; //删除时,此行调用AcceptChanges后已从集合中删除,所以索引需要-1。
break;
case DataRowState.Added:
if (PublicUpdateDataBaseEvents(r))
continue;
sql.Append(SQLBuilder.GetInsertSql(r));
r.AcceptChanges();
break;
case DataRowState.Modified:
if (PublicUpdateDataBaseEvents(r))
continue;
sql.Append(SQLBuilder.GetUpdateSql(r));
r.AcceptChanges();
break;
}
}
/// <summary>
/// 生成删除语句。
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public static string GetDeleteSql(DataRow row)
{
if (row.Table.PrimaryKey == null || row.Table.PrimaryKey.Length == 0)
{
throw new Exception("SQLBuilder:没有定义主键,无法生成删除语句!");
}
StringBuilder sql = new StringBuilder();
sql.AppendFormat("delete from {0} where 1=1", row.Table.TableName);
foreach (DataColumn dc in row.Table.PrimaryKey)
{
if (row.IsNull(dc, DataRowVersion.Original))
{
sql.AppendFormat(" and {0} is null", dc.ColumnName);
continue;
}
if (dc.DataType == typeof(int) || dc.DataType == typeof(decimal) ||
dc.DataType == typeof(float) || dc.DataType == typeof(double) ||
dc.DataType == typeof(byte))
{
sql.AppendFormat(" and {0}={1}", dc.ColumnName, row[dc, DataRowVersion.Original]);
}
else if (dc.DataType == typeof(string) || dc.DataType == typeof(DateTime) ||
dc.DataType == typeof(char))
{
sql.AppendFormat(" and {0}='{1}'", dc.ColumnName, FilterValue(row[dc, DataRowVersion.Original]));
}
else
{
throw new Exception("SQLBuilder.GetDeleteSql:未知的数据类型,无法生成删除语句!");
}
}
sql.Append(";");
return sql.ToString();
}