我正在使用C#,MS Access作爲database.I創建類與數據庫中的表相同的屬性,並試圖更新數據庫通過此類使用反射和類鍵值更新where
條件更新目的。以下是方法,處理這個問題:更新命令更新錯誤值
public void UpdateDBByObject(object objClass, string key, object keyValue, string tableName = null)
{
string _updateQuery = string.Empty;
Type objType = objClass.GetType();
List<PropertyInfo> propertyList = new List<PropertyInfo>(objType.GetProperties());
Dictionary<string, object> _props = new Dictionary<string, object>();
_updateQuery += "update " + (string.IsNullOrEmpty(tableName) ? objType.ToString().Split('.').LastOrDefault().TrimEnd('s') : tableName) + " set";
foreach (var prop in propertyList)
{
string _name = prop.Name;
if (_name == key) continue;
_updateQuery += " [" + _name + "] = ?,";
_props.Add(_name, prop.GetValue(objClass, null));
}
_updateQuery = _updateQuery.TrimEnd(',');
_updateQuery += " where " + key + " = ?";
OleDbCommand cmd = new OleDbCommand();
OleDbConnection conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = _updateQuery;
foreach (string value in _props.Keys)
{
object _addValue;
cmd.Parameters.AddWithValue("@" + value, _props.TryGetValue(value, out _addValue));
}
cmd.Parameters.AddWithValue("@" + key, keyValue);
conn = GetOpenConnection();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
CloseConnection(conn);
}
這種方法工作,但在數據庫中更新錯誤的值,即對於字符串值,將其更新爲「-1」的值,日期時間將其更新分鐘DateTime值。請找出錯誤並讓我知道。
props.TryGetValue(值,出_addValue)布爾 – Priyank
@ankush凱卡倫rahilat bhau他...... vadhiv編程...麻辣ghanta zepat nahiye凱lihilay代碼返回 –
@ F.R.I.E.N.D.S。 mala pan que madhe ithka motha code takaychi ichha hot navti,pan que mag瞭解pan zal nasta n manun thakun dilla ..! –