C#返回数据对象问题
我试图从数据库返回一个数据对象,以便访问(例如)ASP.NET网站中的客户ID。当客户登录时,返回该对象。但是,我得到了一个错误:C#返回数据对象问题,c#,sql,object,C#,Sql,Object,我试图从数据库返回一个数据对象,以便访问(例如)ASP.NET网站中的客户ID。当客户登录时,返回该对象。但是,我得到了一个错误: 'Invalid attempt to read when no data is present.' 我已经完成了对数据库的sql查询(执行我的存储过程),返回了正确的信息,所以我知道它就在那里。我只能假设以下方法有问题: using (SqlConnection sqlConn = new SqlConnection(ConfigurationM
'Invalid attempt to read when no data is present.'
我已经完成了对数据库的sql查询(执行我的存储过程),返回了正确的信息,所以我知道它就在那里。我只能假设以下方法有问题:
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand sqlComm = new SqlCommand("Select_Customer_By_UserName_And_Password", sqlConn))
{
sqlComm.Connection.Open();
try
{
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.Add("@Username", SqlDbType.NVarChar, 25).Value = pUsername;
sqlComm.Parameters.Add("@Password", SqlDbType.NVarChar, 25).Value = pPassword;
using (SqlDataReader sqlDR = sqlComm.ExecuteReader(CommandBehavior.SingleRow))
{
if (sqlDR.HasRows)
{
//Creating the new object to be returned by using the data from the database.
return new Customer
{
CustomerID = Convert.ToInt32(sqlDR["CustomerID"])
};
}
else
return null;
}
}
catch (Exception)
{
throw;
}
finally
{
sqlComm.Connection.Close();
}
}
}
您需要调用
sqlDR.Read()
,否则“记录指针”将指向记录HasRows
仅表示实际上有可以读取的行。要读取每一行(或仅第一行),需要调用read
一次或在while
循环中调用
例如:
if (reader.HasRows)
{
while (reader.Read())
...
}
您的代码应为:
using (SqlDataReader sqlDR = sqlComm.ExecuteReader(CommandBehavior.SingleRow))
{
if (sqlDR.Read())
{
//Creating the new object to be returned by using the data from the database.
return new Customer
{
CustomerID = Convert.ToInt32(sqlDR["CustomerID"])
};
}
else
return null;
}
顺便说一句:祝贺您使用和参数化查询