0
我有ado.net操作的基類,看起來像這樣:如何將數據讀取器中的數據讀入數據表?
public abstract class BaseDataAccess
{
private string _connectionString = ......
protected string ConnectionString
{
get { return _connectionString; }
}
protected object ExecuteScalar(string spName, SqlParameter[] parameters=null)
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
using (SqlCommand command = new SqlCommand(spName, connection))
{
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
command.CommandType = System.Data.CommandType.StoredProcedure;
connection.Open();
return command.ExecuteScalar();
}
}
}
protected DataTable ExecuteReader(string spName, SqlParameter[] parameters=null)
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
using (SqlCommand command = new SqlCommand(spName, connection))
{
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
command.CommandType = CommandType.StoredProcedure;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
DataTable table = new DataTable();
table.Load(reader);
return table;
}
}
}
}
}
而且,查詢用戶表類
public class UsersAccess : BaseDataAccess
{
private const string SP_COUNT_USERS = "spCountUsers";
private const string SP_GET_USERS = "spGetUsers";
public int CountUsers()
{
return (int)base.ExecuteScalar(SP_COUNT_USERS);
}
public IList<User> GetUsers()
{
DataTable usersTable = base.ExecuteReader(SP_GET_USERS);
return GetUsersFromDataTable(usersTable);
}
private IList<User> GetUsersFromDataTable(DataTable usersTable)
{
IList<User> users = new List<User>();
foreach (DataRow row in usersTable.Rows)
{
User user = new User();
user.UserID = (int)row["UserID"];
user.Password = (string)row["Password"];
user.Username = (string)row["Username"];
}
return users;
}
}
數據讀取器配有2行數據,但當沒有數據進入數據表時。 如何做到這一點?
PS:對於更好的ado.net基類,任何提示都會很棒。我只有幾張桌子,只有很少的程序/桌子。
你可以嘗試DataAdapter.Fill方法方法結束,雖然我沒有看到一個很好的理由,爲什麼你當前的代碼不起作用。 (http://msdn.microsoft.com/en-us/library/497b1k4t.aspx) – 2012-08-09 20:52:23