我想将数据库逻辑与应用程序分开,所以我写了一个添加记录的函数:
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>");
}
}
问题是哈希表将数据存储为对象数据类型。我希望能够拥有一个添加记录并传入参数的函数。有什么办法可以做到这一点?