这个数据库交互的类我是以单例模式实现的,"_"开头的都是已经生成唯一的实例。 旧数据用sql语句查询出的dataTable,发生改变后dataTable(增加,删除,修改),增改是利用OracleCommandBuilder自身Update(table),它可以实现增加和修改(需要主键)。 删除是利用旧datable与修改后的datable之间取交差,获取需要删除的数据。
/// <summary>
/// datatable与数据库的增删改的实现
/// </summary>
/// <param name="table"></param>
/// <param name="CommandText">sql语句</param>
/// <param name="key"></param>
/// <param name="tableName"></param>
/// <returns></returns>
public int UpdateAndDeleteTable(DataTable table, string CommandText,string key,string tableName)
{
//更新和新增
OracleCommandBuilder ocb = new OracleCommandBuilder(_oracleDataAdapter);
_oracleDataAdapter.SelectCommand.CommandText = CommandText;
_oracleDataAdapter.InsertCommand = ocb.GetInsertCommand();
int updete=_oracleDataAdapter.Update(table);
//删除:差集删除
DataTable oldTable = this.GetDataTable(CommandText);
var query = oldTable.AsEnumerable().Except(table.AsEnumerable(), DataRowComparer.Default);
if (query.Count()==0)
{
return updete;
}
StringBuilder sb = new StringBuilder();
sb.Append($"delete {tableName} where {key} in(");
foreach (var row in query)
{
sb.Append("'"+row[key].ToString()+"',");
}
sb.Remove(sb.Length - 1, 1);
sb.Append(")");
string sql = sb.ToString();
int delete = ExcuteSql(sql);
return updete+ delete;
}
|