创建 'INSERT INTO' SQL 查询的 C# 类






2.49/5 (23投票s)
2004年12月16日

175494

2
用于创建 INSERT INTO SQL 查询的类。
引言
本文描述了一个 C# 类,用于创建 INSERT INTO
SQL 查询。
几天前,我被迫处理一个用 FoxPro for DOS 编写的旧应用程序。这意味着要处理 DBF 文件。我使用了 OleDB for FoxPro。它运行良好,但在需要将行插入到包含 50 列(或更多)的表中时,我遇到了麻烦。我必须在 INSERT
查询中指定所有列。太可怕了。
所以我编写了一个小类来为我创建查询。它很短,代码如下
public class Insert
{
Hashtable args = new Hashtable();
string table;
/// <summary>
/// Constructs Insert object
/// </summary>
/// <param name="table">table name to insert to</param>
public Insert(string table)
{
this.table = table;
}
/// <summary>
/// Adds item to Insert object
/// </summary>
/// <param name="name">item name</param>
/// <param name="val">item value</param>
public void Add(string name, object val)
{
args.Add(name, val);
}
/// <summary>
/// Removes item from Insert object
/// </summary>
/// <param name="name">item name</param>
public void Remove(string name)
{
try
{
args.Remove(name);
}
catch
{
throw (new Exception("No such item"));
}
}
/// <summary>
/// Test representatnion of the Insert object (SQL query)
/// </summary>
/// <returns>System.String</returns>
public override string ToString()
{
StringBuilder s1 = new StringBuilder();
StringBuilder s2 = new StringBuilder();
IDictionaryEnumerator enumInterface = args.GetEnumerator();
bool first = true;
while(enumInterface.MoveNext())
{
if (first) first = false;
else
{
s1.Append(", ");
s2.Append(", ");
}
s1.Append(enumInterface.Key.ToString());
s2.Append(enumInterface.Value.ToString());
}
return "INSERT INTO " + table + " (" + s1 + ") VALUES (" + s2 + ");";
}
/// <summary>
/// Gets or sets item into Insert object
/// </summary>
object this[string key]
{
get
{
Debug.Assert(args.Contains(key), "Key not found");
return args[key];
}
set {args[key]=value;}
}
}
你可以这样使用它
Insert q = new Insert("table_name");
q.Add("column1", "value1");
q.Add("column2", "value2");
string query = q.ToString();
如果你的列数超过 50 列,并且每一列都以某种方式计算得出,这会很有用。抱歉我的英语不好;)