自己写了一段程序,练习一下使用c#封装sql语句。
namespace Model
{
using System.Reflection;
using DAL;
abstract public class DBModel
{
public DBModel()
{
_updateFiled = new List<string>();
_valueFiled = new List<string>();
}
#region 更新
virtual public int UpdateByKey()
{
string sql = GetUpdateByKeySql();
return DBHelper.ExecuteNonQuery(sql);
}
// 获得更新的SQL语句
private string GetUpdateByKeySql()
{
string updateSql = "UPDATE {0} SET {1} WHERE {2} = '{3}'";
string keyFiled, keyValue;
if (GetPrimaryKeyInfo(out keyFiled, out keyValue))
{
return string.Format(updateSql, _tbName, GetUpdateFieldAndValueString(), keyFiled, keyValue);
}
else
{
return "";
}
}
/// <summary>
/// 获得更新数据库的SQL字段和值
/// </summary>
/// <returns>更新数据库的部分字符串</returns>
private string GetUpdateFieldAndValueString()
{
GetDbFieldAndValue();
string strUpdateValue = "";
for (int iLoop = 0; iLoop < _updateFiled.Count; iLoop++)
{
strUpdateValue += _updateFiled[iLoop];
strUpdateValue += "='";
strUpdateValue += _valueFiled[iLoop];