我想将数据库逻辑与应用程序逻辑分开,所以我写了一个添加记录的函数:
public static bool AddRecordToDB(string tableName,Hashtable ht)
{
try
{
using (SqlConnection conn = CreateSqlConnection())
{
SqlDataAdapter sda = new SqlDataAdapter("Select * from " + tableName + "where 0=1;", conn);
DataSet ds = new DataSet();
sda.Fill(ds, tableName);
//Create new record
DataRow newRow = ds.Tables[tableName].NewRow();
foreach (DictionaryEntry de in ht)
{
newRow[de.Key.ToString()] = de.Value;
}
//Add new row to dataset
ds.Tables[tableName].Rows.Add(newRow);
new SqlCommandBuilder(sda);
sda.Update(ds, tableName);
}
}
catch (Exception ex)
{
return false;
}
return true;
}
并在此处使用
protected void btnSave_Click(object sender, EventArgs e)
{
string tableName = "TestTable";
Hashtable ht = new Hashtable();
ht.Add("FirstNumber", Double.Parse(txtFirstNum.Text));
ht.Add("SecondNumber", Double.Parse(txtSecondNum.Text));
ht.Add("Operator", DropDownListOp.SelectedValue);
ht.Add("Result", Double.Parse(txtResults.Text));
if(SQL.AddRecordToDB(tableName,ht))
{
Response.Write(@"<script>alert('" + Server.HtmlEncode("Save successful!") + "');document.location.href='WebForm1.aspx';</script>");
}
else
{
Response.Write(@"<script>alert('" + Server.HtmlEncode("Save Failed!") + "');document.location.href='WebForm1.aspx';</script>");
}
}
问题是hashtables将数据存储为对象数据类型。我希望能够有一个将添加记录的函数,并传递参数。有什么方法可以实现这个目标吗?
答案 0 :(得分:0)
一般来说,你应该避免像这样的弱类型方法来实现'伪解耦'。在这种情况下,我肯定会使用一个业务对象,其中包含填充DataRow的四个字段。只要您的View代码直接与DAL一起工作,几乎不可能实现高级别的解耦,但无论如何,在这种情况下使用业务对象更容易出错并且类型安全。 同意在传递Hashtable of Object值以填充表时,您必须知道每个列表示的数据类型,因此您不能使用单个泛型方法将任意值传递给任意表,假设它们将匹配。也许您还应该考虑实现一个简单的MVC(模型视图控制器)模式,以便真正地将GUI与数据库分离。在这种模式下,互联网上有很多很好的例子。