没有数据时无效尝试读取数据

时间:2013-09-11 15:11:11

标签: c# asp.net sql sql-server

我在C#中有一个SQL Server数据库[在我完成目前的工作之前建立,创建者已经不见了],直到上周它还没有。在第一页clerk_search.aspx上,它搜索SQL Server以查找人员并发回数据网格,这很好。

点击了一个ASP Image按钮,然后转到下一页,输入客户访问的原因,其中包含有关回发客户的已加载字段。对于某些人来说,下一页填充,而对于其他人则不填充。使用的SQL语句在查询分析器中检查出来,我不明白。我不认为它是读者,因为其他人登录得很好,而其他客户都存在于SQL的行中,可以很好地查询。全部发布在下面,我不精通编码,请协助。

  

System.InvalidOperationException:没有数据时读取的尝试无效。

     

SqlDataReader reader2 = cmd.ExecuteReader();
  reader2.Read();

     

[InvalidOperationException:没有数据时读取的尝试无效。]

以下是实际:.... clerk_create.aspx.cs

 public partial class clerk_create : System.Web.UI.Page
 {
     protected void Page_Load(object sender, EventArgs e)
     {
        if (Request.Cookies["us"] == null)
         {
             Response.Write("Sorry, you do not have access to this page. Please see    
 data systems.");
             Response.End();
         }

        if (!IsPostBack)
        {
            using (SqlConnection connection = new SqlConnection    
 (WebConfigurationManager.ConnectionStrings["walkin2"].ConnectionString))
            {
                TextBox txtsct = (TextBox)Page.PreviousPage.FindControl("Txtsct");
                Txtsct.Text = txtsct.Text; 
                TextBox txt = (TextBox)Page.PreviousPage.FindControl("Txtssn");
                Txtssn.Text = "" + txt.Text;
                connection.Open();
                string strsql2 = "SELECT dbo.table_name.SSN,   
                dbo.table_name.LAST_NAME,      
                dbo.table_name.FIRST_NAME, dbo.table_name.MIDDLE_INITIAL, 
                dbo.table_name.COMPONENT_CODE, dbo.table_name.PRESENT_CODE FROM 
                dbo.table_name INNER JOIN dbo.table_name ON dbo.table_name.SSN = '" + 
                Txtssn.Text + "')";
                SqlCommand cmd = new SqlCommand(strsql2, connection);
                SqlDataReader reader2 = cmd.ExecuteReader();
                reader2.Read();
                LblLName.Text = "" + reader2["LAST_NAME"];
                LblFName.Text = "" + reader2["FIRST_NAME"];
            }
        }
    }
 ...
}

2 个答案:

答案 0 :(得分:3)

您应该检查Read方法的返回值。

如果read方法返回false,则不再有数据。在这种情况下,您不应该从阅读器中读取数据。这样做会导致此异常。

如果您确定只能获得一条记录,请尝试使用

if(reader2.Read())
{
    LblLName.Text = "" + reader2["LAST_NAME"];
    LblFName.Text = "" + reader2["FIRST_NAME"];
}
通常DataReader通常使用while (reader2.Read()) { //Consume reader using reader2["Column"] etc } ,因为它可以包含多个记录

{{1}}

答案 1 :(得分:0)

您的代码未正确处理某些对象,并且容易受到SQL injection的攻击。<​​/ p>

DTO:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

代码:

private static readonly Lazy<string> ConnectionString = new Lazy<string>(() => WebConfigurationManager.ConnectionStrings["walkin2"].ConnectionString);
private const string GetEmployeeBySSNQuery = "SELECT dbo.table_name.SSN, dbo.table_name.LAST_NAME, dbo.table_name.FIRST_NAME, dbo.table_name.MIDDLE_INITIAL, dbo.table_name.COMPONENT_CODE, dbo.table_name.PRESENT_CODE FROM dbo.table_name INNER JOIN dbo.table_name ON dbo.table_name.SSN = @SSN";

protected void Page_Load(object sender, EventArgs e)
{
    // ...
    if(!IsPostBack)
    {
        GetEmployeeInformation();
    }
}

private void GetEmployeeInformation()
{
    var sctTextBox = (TextBox)Page.PreviousPage.FindControl("Txtsct");
    Txtsct.Text = txtsct.Text; 
    var ssnTextBox = (TextBox)Page.PreviousPage.FindControl("Txtssn");
    Txtssn.Text = ssnTextBox.Text;

    var ssn = ssnTextBox.Text;

    var employee = GetEmployeeBySSN(ConnectionString.Value, ssn);

    if(employee != null)
    {
        LblFName.Text = employee.FirstName;
        LblLName.Text = employee.LastName;
    }
}

private Employee GetEmployeeBySSN(string connectionString, string ssn)
{
    Employee employee = null;

    using(var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        using(var command = new SqlCommand(GetEmployeeBySSNQuery, connection)
        {
            command.Parameters.AddWithValue("@SSN", ssn);

            using(var reader = command.ExecuteReader())
            {
                if(reader.Read())
                {
                    employee = new Employee
                                {
                                    FirstName = Convert.ToString(reader["FIRST_NAME"]),
                                    LastName = Convert.ToString(reader["LAST_NAME"])
                                };
                }
            }
        }
    }

    return employee;
}