简体   繁体   English

使用SQLDataReader时,“在没有数据的情况下读取尝试无效”

[英]“Invalid attempt to read when no data is present” when using SQLDataReader

Here is my GeneralFunctions: 这是我的GeneralFunctions:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for GeneralFunctions
/// </summary>
public class GeneralFunctions
{
    public GeneralFunctions ()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static DataTable GetData ( string query )
    {
        SqlDataAdapter dataAdapter;
        DataTable table;

        try
        {
            dataAdapter = new SqlDataAdapter( query, GetConnectionString() );
            table = new DataTable();

            dataAdapter.Fill( table );
            return table;
        }
        catch ( Exception ex )
        {
        }
        finally
        {
            dataAdapter = null;
            table = null;
        }

        return table;
    }

    private static string GetConnectionString ()
    {
        string connectionString = ConfigurationManager.ConnectionStrings[ "CAPortalConnectionString" ].ConnectionString;

        return connectionString;
    }

    public static int? AuthenticateLogin ( string username, string password )
    {
        using ( var conn = new SqlConnection( GetConnectionString() ) )
        using ( var cmd = conn.CreateCommand() )
        {
            conn.Open();
            cmd.CommandText =
            @"SELECT 
                 DistID 
             FROM 
                 Distributor
             WHERE 
                 Username = @username 
             AND 
                 Password = @password";
            cmd.Parameters.AddWithValue( "@username", username );
            cmd.Parameters.AddWithValue( "@password", password );
            using ( var reader = cmd.ExecuteReader() )
            {
                if ( !reader.Read() )
                {
                    // no results found
                    return null;
                }
                return reader.GetInt32( reader.GetOrdinal( "DistID" ) );
            }
        }
    }

    public static string GetDistInfo ( int distID )
    {
        using ( var conn = new SqlConnection( GetConnectionString() ) )
        using ( var cmd = conn.CreateCommand() )
        {
            conn.Open();
            cmd.CommandText =
            @"SELECT 
                 FName + ' ' + LName AS Name
             FROM 
                 Distributor
             WHERE 
                 DistID = @distid";
            cmd.Parameters.AddWithValue( "@distid", distID );
            using ( var reader = cmd.ExecuteReader() )
            {
                return reader.GetString( reader.GetOrdinal( "Name" ) );
            }
        }
    }

}

Here is my login page: 这是我的登录页面:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class index : System.Web.UI.Page
{
    protected void Page_Load ( object sender, EventArgs e )
    {

    }
    protected void but_login_Click ( object sender, EventArgs e )
    {
        if ( username_id.Text != "" || password.Text != "" )
        {
            // Verify the username and password match the database
            var distId = GeneralFunctions.AuthenticateLogin( username_id.Text, password.Text );

            if ( distId != null )
            {
                // User is authenticated
                var name = GeneralFunctions.GetDistInfo( (int)distId );
                Session[ "DistName" ] = name;
                Session[ "DistID" ] = distId;

                Response.Redirect( "dashboard.aspx", false );
            }
            else
            {
                // provide error label here username and password do not match
                authentFailed.Text = "Username / Password did not match our records";
            }
        }
        else
        {
            // Username or Password blank error lable
            authentFailed.Text = "Please Input Username / Password";
        }
    }
}

Before I added the GetDistInfo method it worked just fine, logged in the user. 在我添加GetDistInfo方法之前,它已经可以正常工作了,并登录到用户中。 I then tried to add Session variables and the GetDistInfo method. 然后,我尝试添加会话变量和GetDistInfo方法。 I pass in the DistID returned from AuthenticateLogin into the GetDistInfo method. 我将从AuthenticateLogin返回的DistID传递到GetDistInfo方法中。 It errors out with the following error: 它错误并显示以下错误:

Exception Details: System.InvalidOperationException: Invalid attempt to read when no data is present. 异常详细信息:System.InvalidOperationException:不存在任何数据时尝试进行无效的读取。

Source Error:

Line 95:             using ( var reader = cmd.ExecuteReader() )
Line 96:             {
Line 97:                 return reader.GetString( reader.GetOrdinal( "Name" ) );
Line 98:             }
Line 99:         }


Source File: c:\inetpub\wwwroot\Base\ClientAccessPortal\App_Code\GeneralFunctions.cs    Line: 97 

When I run the SQL against the database it correct pulls back the clients name. 当我对数据库运行SQL时,它正确地拉回了客户端名称。 I'm not sure why it isn't doing that inside the code. 我不确定为什么它不在代码内执行。 Anyone able to see what I am missing? 有人能看到我所缺少的吗?

Please try replacing this. 请尝试更换它。 Actually Read() was missing in your code. 实际上,您的代码中缺少Read()

using ( var reader = cmd.ExecuteReader() )
{
     return reader.GetString( reader.GetOrdinal( "Name" ) );
}

With following 随着以下

using ( var reader = cmd.ExecuteReader() )
{
     if(reader.Read())
     {
          return reader.GetString( reader.GetOrdinal( "Name" ) );
     }
     return null;
}

You need to read first (you're doing it when using the reader above in your code): 您需要先阅读(在代码中使用上面的阅读器时,您需要这样做):

using ( var reader = cmd.ExecuteReader() )
{
    // you haven't positioned yourself on a record yet.
    while (reader.Read())
    {
        return reader.GetString( reader.GetOrdinal( "Name" ) );
    }
    return string.Empty;
}

EDIT To respond to the error you got; 编辑以响应您得到的错误; since you define your function 因为您定义了功能

public static string GetDistInfo ( int distID )

all possible ways "out of the function" must return something. 所有“超出功能范围”的可能方式都必须返回某些内容。 In your case you should return a string or maybe null depending on what you want to do. 在您的情况下,您应该返回一个字符串,或者返回null,这取决于您要执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM