我使用的是SqlDataReader,在尝试读取阅读器时遇到了行。
当我选中.HasRows时,行不可用。
List<EmployeeTimings> empTimingsList = new List<EmployeeTimings>();
// Creates a SQL connection
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["WINPAKContext"].ToString()))
{
// Creates a SQL command
using (var command = new SqlCommand("SELECT * FROM SEED_VIEW WHERE empid is not null and DateTime > '" + dtlastpunch + "' order by datetime", connection))
{
connection.Open();
// Loads the query results into the table
var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
EmployeeTimings empTime = new EmployeeTimings();
empTime.CardNumber = reader["CardNO"].ToString();
empTime.EMPId = reader["EMPID"].ToString();
empTime.FirstName = reader["FirstName"].ToString();
empTime.LastName = reader["LastName"].ToString();
empTime.Location = reader["Location"].ToString();
empTime.Trans_DateTime = Convert.ToDateTime(reader["DateTime"]);
empTimingsList.Add(empTime);
}
reader.Close();
}
command.ExecuteNonQuery();
}
connection.Close();
}
return empTimingsList;你能告诉我有什么问题吗?
在reader.HasRows()调用之后发生了什么,redaer没有任何行...
发布于 2016-01-08 16:37:01
不需要检查HasRow属性,只要Read就足够了,如果您使用just read方法并尝试从没有任何行的读取器中读取行,那么它将只存在while循环
你可以这样写,删除hasRow是不需要的
while (reader.Read())
{
EmployeeTimings empTime = new EmployeeTimings();
empTime.CardNumber = reader["CardNO"].ToString();
empTime.EMPId = reader["EMPID"].ToString();
empTime.FirstName = reader["FirstName"].ToString();
empTime.LastName = reader["LastName"].ToString();
empTime.Location = reader["Location"].ToString();
empTime.Trans_DateTime = Convert.ToDateTime(reader["DateTime"]);
empTimingsList.Add(empTime);
}避免SQLInjection
除此之外,你的代码将允许SQLInjection,因为你直接在query...Make中传递值,使用参数化查询,而不是像这样的代码。
查询中的datetime条件的问题
在未应用任何转换情况下比较where条件中的DateTime值时,可能会出现问题。如果您使用参数化sql查询,此问题将得到解决。
发布于 2016-01-08 16:37:13
正如你在这里看到的,https://msdn.microsoft.com/ru-ru/library/system.data.datatablereader.hasrows%28v=vs.110%29.aspx -你的代码看起来不错。尝试调查返回的数据集。
发布于 2016-01-08 16:38:02
只需移除整个包装块即可
if (reader.HasRows)
{
...
}您的代码将保持相同的功能,并且您不必担心HasRows :)
再说一句。请删除代码中的以下行:
command.ExecuteNonQuery();https://stackoverflow.com/questions/34672573
复制相似问题