C# 使用c中的存储过程从数据库获取记录
我试图使用存储过程从数据库中获取记录,但它在SqlDataReader对象中返回null 这是我的密码:C# 使用c中的存储过程从数据库获取记录,c#,sql-server,stored-procedures,C#,Sql Server,Stored Procedures,我试图使用存储过程从数据库中获取记录,但它在SqlDataReader对象中返回null 这是我的密码: public Buybest_Liberary.Data.UserManagement getUser(string email) { Buybest_Liberary.Data.UserManagement obj = new Buybest_Liberary.Data.UserManagement(); string conString = @"Data Source=(
public Buybest_Liberary.Data.UserManagement getUser(string email)
{
Buybest_Liberary.Data.UserManagement obj = new Buybest_Liberary.Data.UserManagement();
string conString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ahmadshair\Documents\Buybest.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand _cmd = new SqlCommand("getUserRecord", connection);
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = email;
SqlDataReader dr = _cmd.ExecuteReader();
if (dr.HasRows)
{
obj.UId = Convert.ToInt32(dr[0]);
obj.Email = dr[1].ToString();
obj.Password = dr[2].ToString();
}
return obj;
}
如果我没有弄错的话,您丢失了获取第一条记录的dr.Read。您需要在访问数据之前调用dr.Read!另外:将您的一次性对象SqlConnection、SqlCommand、SqlDataReader放入使用。。{…}块以确保正确处理:
public Buybest_Liberary.Data.UserManagement getUser(string email)
{
Buybest_Liberary.Data.UserManagement obj = new Buybest_Liberary.Data.UserManagement();
// You should read the connection string from a config file
// don't specify it explicitly in code!
string conString = ConfigurationManager.ConnectionStrings["-your-connection-string-name-here-"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conString))
using (SqlCommand _cmd = new SqlCommand("getUserRecord", connection))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = email;
connection.Open();
using (SqlDataReader dr = _cmd.ExecuteReader())
{
// the SqlDataReader could return *multiple* rows - how are you
// going to deal with that? Create an object for each row of data
// and add them to a list to return?
while (dr.Read())
{
obj.UId = Convert.ToInt32(dr[0]);
obj.Email = dr[1].ToString();
obj.Password = dr[2].ToString();
}
dr.Close();
}
connection.Close();
}
return obj;
}
另外:如果存储过程返回多行数据,该怎么办?您也需要以某种方式处理这一问题,HasRows只是告诉您是否有任何行要读取,而read将内部光标提前到数据中的下一行,如果没有更多行要读取,则顺便返回False,如果有其他行可用,则返回True。
我们需要dr.readgetUserRecord的定义是什么?你真的确定它会返回一些数据吗?另外,不要硬编码连接字符串。从配置文件中读取它。无需调用dr.Close或connection.Close,因为dr和connection都包含在using中blocks@JesúsLópez:同意-连接字符串是从问题中复制的-不是我做的。是的,没有严格的必要打电话给Close博士或connection博士。Close-但这样做也不会有什么伤害-我更喜欢直言不讳。没关系。不过,我认为最好是向新手传授最佳实践,而不是直接回答问题。谢谢,这很有帮助。