Fetching database records and displaying as JSON. Asking for revision to ensure if everything's ok, i.e. connections are properly handled and closed in case of error.
public class Department
{
public Department(int id, String name)
{
this.Id = id;
this.Name = name;
}
public int Id { get; set; }
public String Name { get; set; }
}
public List<Department> FindAllDepartment()
{
List<Department> rows = new List<Department>();
using (SqlConnection sqlConnection = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;pooling=true"))
{
SqlCommand command = new SqlCommand("SELECT * FROM Employees.dbo.Department", sqlConnection);
try
{
sqlConnection.Open();
using (SqlDataReader sqlDataReader = command.ExecuteReader())
{
while (sqlDataReader.Read())
rows.Add(new Department(sqlDataReader.GetInt32(0), sqlDataReader.GetString(1)));
}
return rows;
}
finally
{
sqlConnection.Close();
}
}
}