我们可以在每个函数中对这些重复的代码做些什么吗?就像从一个函数调用全部相同的工作。我是这个asp.net和class的新手。任何想法将不胜感激。
dst
答案 0 :(得分:2)
扰流器:
public class Attendance { // Classes should start with a capital
private readonly string connectionString = WebConfigurationManager.ConnectionStrings["databaseConnection"].ConnectionString;
//<employee>
public DataTable GetEmployeeList() { // Somewhat more clear
string query = "select * from view_emp_info"; // Select * is not recommended. You know the columns. If the schema changes and this fails, you'll at least know why on the spot.
return FetchTable(query);
}
//</employee>
//<promotion>
public DataTable GetPromotionList() { // again, clear method names
string query = "select * from tbl_emp_promotion_detail order by TDate DESC";
return FetchTable(query);
}
private DataTable FetchTable(string query)
{
if( string.IsNullOrWhiteSpace(query) ) throw new ArgumentException();
DataTable dataTable = null;
// make a new connection, auto-close and dispose to avoid trouble
// _unless_ you are using ConnectionPooling
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
dataTable = new DataTable();
dataAdapter.Fill(dataTable);
}
return dataTable;
}
}