0

我想将数据库逻辑与应用程序分开,所以我写了一个添加记录的函数:

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>");
            }

        }

问题是哈希表将数据存储为对象数据类型。我希望能够拥有一个添加记录并传入参数的函数。有什么办法可以做到这一点?

4

1 回答 1

0

一般来说,你应该避免像这样的弱类型方法来实现“伪解耦”。在这种情况下,我肯定会使用一个业务对象,它包含您填充 DataRow 的四个字段。只要您的视图代码直接与 DAL 一起使用,就几乎不可能实现高级别的解耦,但无论如何,在这种情况下使用业务对象更容易出错并且类型安全。同意在传递 Object 值的 Hashtable 以填充表时,您必须了解每列代表的数据类型,因此您不能使用单个通用方法将任意值传递给任意表,假设它们将匹配。也许您还应该考虑实现一个简单的 MVC(模型视图控制器)模式,以便真正将 GUI 与数据库分离。

于 2013-08-23T09:46:28.413 回答