データベース ロジックをアプリケーション ロジックから分離したいので、レコードを追加する関数を作成しました。
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>");
}
}
問題は、ハッシュテーブルがデータをオブジェクト データ型として格納することです。レコードを追加する関数が必要で、パラメーターを渡します。これを達成する方法はありますか?