C# ACCESS的SQL更新数据操作封装类AccessSqlUp
之前发了一个添加操作的封装类,现在继续发一个更新操作的类。
不再需要逐个去set=操作,可以一边判断一边添加,整洁好看好修改,好嗨。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace kqgz.Model
{
class AccessSqlUp
{
private string _tbname = "";
private string _where = "";
public string TbName { get => _tbname; set => _tbname = value; }
public string Where { get => _where; set => _where = value; }
private Hashtable slist = new Hashtable();
public void AddString(string key, string value)
{
if (slist.ContainsKey(key))
{
slist.Remove(key);
}
slist.Add(key, value);
}
private Hashtable dlist = new Hashtable();
public void AddDate(string key, string value)
{
if (dlist.ContainsKey(key))
{
dlist.Remove(key);
}
dlist.Add(key, value);
}
private Hashtable nlist = new Hashtable();
public void AddNull(string key)
{
if (nlist.ContainsKey(key))
{
nlist.Remove(key);
}
nlist.Add(key, null);
}
private Hashtable ilist = new Hashtable();
public void AddInt(string key, int value)
{
if (ilist.ContainsKey(key))
{
ilist.Remove(key);
}
ilist.Add(key, value);
}
public string GetUpdateSql()
{
string sql = "";
if (_tbname == "")
{
return "";
}
int slen = slist.Count;
int dlen = dlist.Count;
int nlen = nlist.Count;
if (slen == 0 && dlen == 0 && nlen == 0)
{
return "";
}
if(Where == "")
{
return "";
}
sql = "update {0} set {1} where " + Where;
sql = sql.Replace("{0}", TbName);
string liestr = "";
//string
foreach (DictionaryEntry de in slist)
{
if (liestr == "")
{
liestr = de.Key.ToString() + "='" + de.Value.ToString() + "'" ;
}
else
{
liestr += "," + de.Key.ToString() + "='" + de.Value.ToString() + "'";
}
}
//date
foreach (DictionaryEntry de in dlist)
{
if (liestr == "")
{
liestr = de.Key.ToString() + "=#" + de.Value.ToString() + "#";
}
else
{
liestr += "," + de.Key.ToString() + "=#" + de.Value.ToString() + "#";
}
}
//null
foreach (DictionaryEntry de in nlist)
{
if (liestr == "")
{
liestr = de.Key.ToString() + "=null";
}
else
{
liestr += "," + de.Key.ToString() + "=null";
}
}
//int
foreach (DictionaryEntry de in ilist)
{
if (liestr == "")
{
liestr = de.Key.ToString() + "=" + de.Value.ToString();
}
else
{
liestr += "," + de.Key.ToString() + "=" + de.Value.ToString();
}
}
sql = sql.Replace("{1}", liestr);
return sql;
}
public void ResetData()
{
slist.Clear();
dlist.Clear();
nlist.Clear();
ilist.Clear();
}
public void ResetTable()
{
TbName = "";
}
}
}
使用方法如下:
AccessSqlUp asql = new AccessSqlUp();
asql.TbName = "userinfo";
asql.Where = " uid=" + ud.uid;
asql.AddString("uno", ghstr);
string sql = asql.GetUpdateSql();
if(sql == "")
{
MessageBox.Show("SQL出现异常", "提示");
return;
}
用着舒服。