C#-SqlDataReader不会返回所有行
作者:互联网
我的SQL命令返回3行,这些行已在SQL Server GUI中验证.我运行完全相同的代码,而SqlDataReader只返回其中的2个.相同的sql命令使用SqlDataAdapter返回3行.
这是我的代码-ds有3行.为了显示差异,我添加了SqlDataAdapter.
提前致谢.
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["VPO"].ConnectionString))
{
string sql = "SELECT DISTINCT A.account_id, A.fname, A.lname,
FROM T_Test1 A WITH (NOLOCK)
JOIN T_Test2 AF WITH (NOLOCK) ON A.Account_id=AF.Account_id
WHERE account_status = 'A' AND A.card IS NOT NULL
AND A.dateFrom >= '09-02-2013 00:00:00'
AND A.dateFrom <= '09-30-2013 00:00:00'
AND AF.code = 'INE'";
SqlCommand command = new SqlCommand(sql.ToString(), connection);
command.CommandTimeout = 3600;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{}
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(command.CommandText, connection);
da.Fill(ds);
}
我找到了解决方案:
using部分的其中一行正在读取第一条记录.在while循环中,它正在从第二条记录中读取.我删除了以下if条件,并且效果很好.谢谢大家的回复.很抱歉没有发布该行,因为我认为该行仅处理异常.
if (!reader.Read())
throw new ApplicationException("MISSING Transaction Returned By Financial Institution. Transaction was not found in the database.");
while (reader.Read()) {}
解决方法:
您可以创建一个类.
public class AccountDetails
{
public int AccountId {get; set;}
public string FName {get; set;}
public string LName {get; set;}
}
然后像这样返回AccontDetails列表…
public List<AccountDetails> GetAccountDetails()
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["VPO"].ConnectionString))
{
string sql = "SELECT DISTINCT A.account_id, A.fname, A.lname,
FROM T_Test1 A WITH (NOLOCK)
JOIN T_Test2 AF WITH (NOLOCK) ON A.Account_id=AF.Account_id
WHERE account_status = 'A' AND A.card IS NOT NULL
AND A.dateFrom >= '09-02-2013 00:00:00'
AND A.dateFrom <= '09-30-2013 00:00:00'
AND AF.code = 'INE'";
SqlCommand command = new SqlCommand(sql.ToString(), connection);
command.CommandTimeout = 3600;
connection.Open();
var accDetails = new List<AccountDetails>();
using (var rdr = command.ExecuteReader())
{
while (rdr.Read())
{
var accountDetails = new AccountDetails{
AccountId = rdr.GetInt32(0),
FName = rdr.GetString(1),
LName = rdr.GetString(2)
};
accDetails.Add(accountDetails);
}
}
}
return accDetails;
}
语法可能像我写一些这样的徒手画出的那样.
除非您特别需要使用数据集,否则这比使用数据集轻.如果是这样,请告诉我,我将更新代码.
标签:c-4-0,ado-net,c,sql-server 来源: https://codeday.me/bug/20191122/2062790.html