我想传递一个方法作为参数来从我的程序中删除重复的代码。这是我想要的功能:
private void sqlQuery(Method sqlMethod)
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
try
{
//open SQL connection
conn.Open();
sqlMethod();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.ToString());
}
finally
{
conn.Close();
}
}
使用:
private void insertTemplate()
{
//create SQL command
SqlCommand insertTemplate = new SqlCommand("INSERT INTO [SavedDescriptionTemplates] (SavedDescription, UserId, CreatedDate) VALUES (@descriptionParam, @userIdParam, @createdDateParam)", conn);
//create and assign parameters
insertTemplate.Parameters.AddWithValue("@descriptionParam", descriptionInput.Text);
insertTemplate.Parameters.AddWithValue("@userIdParam", Int32.Parse(userNameDropDown.SelectedItem.Value));
insertTemplate.Parameters.AddWithValue("@createdDateParam", DateTime.Now);
//execute command and retrieve primary key from the above insert and assign to variable
insertTemplate.ExecuteNonQuery();
}
电话是:
sqlQuery(insertTemplate());
这可能吗?