0

我真的需要你的帮助,我正在做一个学校项目。我使用 SqlDataReader 来存储我的数据,在存储数据后(它可以工作,我在调试 sqldatareader 结果视图时检查了它是否充满了我的数据)当我尝试使用具有所有数据的 sqldatareader 变量时,它直接变为空?在到达 if 行之前,我的 sqlreader 中包含所有数据,但是当我调试 if 行时,它显示 sqlreader 为空!

 class ServicesProvider
    {
     public static SqlConnection connection = new SqlConnection(myprovider);
      public static bool LogInVerification(string NickName,string Password)
        {
            SqlDataReader SqlReader;
            SqlCommand command;
            try
            {
                command = new SqlCommand("Check_LogIn", connection);
                command.CommandType = CommandType.StoredProcedure;

            SqlParameter prm=null;
            prm = new SqlParameter("@Password", SqlDbType.VarChar);
            prm.Value=NickName;
            prm.Direction=ParameterDirection.Input;
            command.Parameters.Add(prm);

            prm = new SqlParameter("@NickName", SqlDbType.VarChar);
            prm.Value=Password;
            prm.Direction=ParameterDirection.Input;
            command.Parameters.Add(prm);

            try
            {
                connection.Open();
                SqlReader = command.ExecuteReader();

                    if (SqlReader["NickName"].ToString()== "1")
                return true;;
            }
            catch (Exception ERROR)
            {
                Console.WriteLine(ERROR.Message);
            }

        }
        catch (Exception error)
        {
            Console.WriteLine(error.Message);
        }
        return false;
    }
}
4

1 回答 1

6

这段代码是问题所在:

SqlReader = command.ExecuteReader();
if (SqlReader["NickName"].ToString()== "1")

返回时ExecuteReader,阅读器位于第一个结果之前。你需要打电话Read来阅读结果。通常是:

using (SqlDataReader reader = command.ExecuteReader())
{ 
    while (reader.Read())
    {
        // Handle the data for this row
    }
}

笔记:

  • 如果您只想读取单个值,请考虑使用ExecuteScalar
  • You should have a using statement for each disposable resource (the connection, the command, the reader)
  • Local variables are conventionally camelCased (not PascalCased like SqlReader)
  • Using a single static connection is a really bad idea. Create the connection and open it each time you want to perform a database operation, and dispose it when you're done with that operation (which will happen automatically with a using statement)
  • It looks like you're probably storing passwords in plain text. This is obviously a huge security problem.
于 2013-03-30T17:05:41.520 回答