此方法只要傳入表名,字段名,跟值就好了,不用寫sql語句,很大程度的節省了開發時間,與代碼量
建一個類文件,方便調用,
/// <summary>
/// 執行sql插入語句,返回受影響的行數
/// </summary>
/// <param name="TableName">要插入的表名</param>
/// <param name="ct">操作類型</param>
/// <param name="dic">字段名數組</param>
/// <returns></returns>
public int Insert(string TableName, CommandType ct,Dictionary<string,object> dic)
{
string str1 = "", str2 = "";
if (dic.Count > 0)
{
open();
SqlCommand comm = new SqlCommand();
foreach (KeyValuePair<string, object> kvp in dic)//遍歷數組的key,value;
{
comm.Parameters.Add(new SqlParameter("@" + kvp.Key, kvp.Value));
if (str1 == "" && str2 == "")
{
str1 += kvp.Key;
str2 += "@" + kvp.Key;
}
else
{
str1 += "," + kvp.Key;
str2 += ",@" + kvp.Key;
}
}
try
{
comm.CommandText = "insert into " + TableName + "(" + str1 + ") values (" + str2 + ")";
comm.Connection = conn;
comm.CommandType = ct;
int i = comm.ExecuteNonQuery();
return i;
}
catch { return 0; }
finally
{
close();
}
}
else
{
return 0;
}
}
/// <summary>
/// 執行sql修改語句,返回受影響的行
/// </summary>
/// <param name="TableName">要修改的表名</param>
/// <param name="ct">操作類型</param>
/// <param name="dic">字段名數組</param>
/// <param name="where">條件語句</param>
/// <returns></returns>
public int Update(string TableName, CommandType ct, Dictionary<string, object> dic, string where)
{
string str = "";
if (dic.Count > 0)
{
open();
SqlCommand comm = new SqlCommand();
foreach (KeyValuePair<string, object> kvp in dic)
{
comm.Parameters.Add(new SqlParameter("@" + kvp.Key, kvp.Value));
if (str == "")
{
str += kvp.Key + "=@" + kvp.Key;
}
else
{
str += "," + kvp.Key + "=@" + kvp.Key;
}
}
try
{
comm.CommandText = "update " + TableName + " set " + str + " where " + where;
comm.Connection = conn;
comm.CommandType = ct;
int i = comm.ExecuteNonQuery();
return i;
}
catch { return 0; }
finally
{
close();
}
}
else
{
return 0;
}
}
上面是類文件的代碼,這裏是調用的方法
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("Title", ProductTitle);
dic.Add("addtime", AddTime);
//新建一個Dictionary數組,第一個參數爲鍵值,我們用來傳字段名;
//第二個參數爲value值,我們用來傳對應的字段的值;
db.Insert("SW_Product", CommandType.Text, dic);
//調用插入的方法,第一個爲表名,第二個爲操作類型,第三個爲數組
int id = cm.ChkClng(Request.QueryString["id"].ToString());
db.Update("SW_Product", CommandType.Text, dic, "id=" + id);
//調用修改的方法,第一個爲表名,第二個爲操作類型,第三個爲數組,第四個爲條件語句
如果大家還有更好的方法,歡迎留言,一起探討;