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>");
}
}
問題是散列表將數據存儲爲對象數據類型。我想能夠有一個功能,將添加記錄,我傳入的參數。有什麼辦法可以做到這一點?
與HashTable相比,您是否有要添加的記錄的具體類型? –
該記錄有4列(3列是雙重類型,一列是varchar數據類型) – coffeeak
它是否表示爲代碼中的類型實例? –