【问题标题】:data reader error with scope_identity query?scope_identity 查询的数据读取器错误?
【发布时间】:2011-04-20 18:09:17
【问题描述】:

当我尝试使用 SqlDataReader 读取我的 scope_identity pk 进行查询以在下一页上显示行数据时,我收到著名的“没有数据时读取的尝试无效”错误消息。这是我第一次使用这两种方法,所以任何提示都会有所帮助。我的代码:

insert command ... ; SELECT SCOPE_IDENTITY() AS [lastInsertedProductId]";

    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        SqlCommand command = new SqlCommand(thisQuery, sqlConn);
        int lastInsertedProductId = Convert.ToInt32(command.ExecuteScalar());
        using (command)
        {
            command.ExecuteNonQuery();
            using (SqlDataReader dr = command.ExecuteReader())
            {
                dr.Read();
                lastInsertedProductId = Convert.ToInt32(dr["lastInsertedProductId"]);
                Response.Redirect("~/View.aspx?ProductId" + lastInsertedProductId);
            }
        }
    }
}

已编辑代码,但现在我在查看页面上看到“'=' 附近的语法不正确,我没有显示实际的语法错误

using (SqlConnection editConn = new SqlConnection(connectionString))
    {
        editConn.Open();

        using (SqlCommand command = new SqlCommand(editQuery, editConn))
        {

            SqlDataReader dr = command.ExecuteReader();
            dr.Read();
            Label6.Text = dr.GetInt32(0).ToString();

【问题讨论】:

  • 我不在 PC 上进行复制,但您读取身份的尝试最好是 original 命令的一部分(即插入)...
  • 在示例中,不清楚每个命令在做什么,或者为什么command会被执行两次......
  • 你也应该用using(...){...} 块包裹你的SqlCommand,并且你不应该在其他一切都设置好之前打开连接 - 尽可能晚打开,马上再次关闭跨度>

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


【解决方案1】:

您必须在插入语句中使用范围标识。喜欢...

INSERT INTO table (ColumnName) VALUES ();SELECT SCOPE_IDENTITY();

就像在你的代码中一样。

SqlCommand command = new SqlCommand(thisQuery, sqlConn);

thisQuery 变量应该在您的插入查询 SELECT SCOPE_IDENTITY();

编辑:我只是在网上查了一下,发现了一种与你正在做的类似的方法,但它会像......

string idQuery = "Select @@Identity"; 

您可以使用此方法完成您的任务,我不知道使用此方法是否有任何限制。但我认为这会奏效。

这是我得到这个http://www.mikesdotnetting.com/Article/54/Getting-the-identity-of-the-most-recently-added-record的网址

【讨论】:

  • @@Identity 的范围更广,我认为是数据库范围的,所以不能保证他得到他要找的身份。
【解决方案2】:

我要感谢所有发布有用答案和建议的人;即使我最终使用了不同的方式,但始终感谢您的帮助。关于这种不同的方式,我决定发布我最终使用的代码,以防有人需要它(尽管没有参数化查询,我希望没有人需要它来完成作业,即使那样......)。因此需要注意的是,以下代码有效,但犯了这里经常谴责的大罪,这是我问题的功能解决方案:

 string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    String thisQuery = "INSERT INTO ProductInstance (CustId, BroId, CustName, SicNaic, CustAdd, CustCity, CustState, CustZip, BroName, BroAdd, BroCity, BroState, BroZip, EntityType, Coverage, CurrentCoverage, PrimEx, Retention, EffectiveDate, Commission, Premium, Comments) VALUES ('" + TbCustId.Text + "', '" + TbBroId.Text + "', '" + TbCustName.Text + "', '" + RblSicNaic.SelectedItem + "', '" + TbCustAddress.Text + "', '" + TbCustCity.Text + "', '" + DdlCustState.SelectedItem + "', '" + TbCustZip.Text + "', '" + TbBroName.Text + "', '" + TbBroAddress.Text + "', '" + TbBroCity.Text + "', '" + DdlBroState.Text + "', '" + TbBroZip.Text + "', '" + DdlEntity.SelectedItem + "', '" + TbCoverage.Text + "','" + TbCurrentCoverage.Text + "','" + TbPrimEx.Text + "','" + TbRetention.Text + "','" + TbEffectiveDate.Text + "','" + TbCommission.Text + "','" + TbPremium.Text + "','" + TbComments.Text + "')";

    string idQuery = "SELECT SCOPE_IDENTITY() AS LastInsertedProductId";
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        SqlCommand command = new SqlCommand(thisQuery, sqlConn);

        SqlCommand idCmd = new SqlCommand(idQuery, sqlConn);
        using (command)
        {

            command.ExecuteNonQuery();               
           command.CommandText=idQuery;
           SqlDataReader dr = command.ExecuteReader();
             dr.Read();
                int lastInsertedProductId = Convert.ToInt32(dr[0]);
                Response.Redirect("~/View.aspx?ProductId=" + lastInsertedProductId);

        }
    }
}
protected void CalEffectDate_SelectionChanged(object sender, EventArgs e)
{
    TbEffectiveDate.Text = CalEffectDate.SelectedDate.ToShortDateString();
}    

} 您会注意到我在重定向中的 ?ProductId 之后缺少一个“=”符号。细节中的魔鬼,不是吗?

以及查看页面代码:

 protected void Page_Load(object sender, EventArgs e)
{
    string x = Request.QueryString["ProductId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string editQuery = "SELECT CustName, SicNaic, CustCity, CustAdd, CustState, CustZip, BroName, BroAdd, BroCity, BroState, BroZip, EntityType, Coverage, CurrentCoverage, PrimEx, Retention, EffectiveDate, Commission, Premium, Comments FROM ProductInstance WHERE ProductId =" + x;

    using (SqlConnection editConn = new SqlConnection(connectionString))
    {
        editConn.Open();

        using (SqlCommand command = new SqlCommand(editQuery, editConn))
        {

            SqlDataReader dr = command.ExecuteReader();
            dr.Read();
            LblCustName.Text = dr.GetString(0);
            LblSicNaic.Text = dr.GetString(1);
            LblCustCity.Text = dr.GetString(2);
            LblCustAddress.Text = dr.GetString(3);
            LblCustState.Text = dr.GetString(4);
            LblCustZip.Text = dr.GetInt32(5).ToString();
            LblBroName.Text = dr.GetString(6);
            LblBroAddress.Text = dr.GetString(7);
            LblBroCity.Text = dr.GetString(8);
            LblBroState.Text = dr.GetString(9);
            LblBroZip.Text = dr.GetInt32(10).ToString();
            LblEntity.Text = dr.GetString(11);
            LblCoverage.Text = dr.GetInt32(12).ToString();
            LblCurrentCoverage.Text = dr.GetInt32(13).ToString();
            LblPrimEx.Text = dr.GetInt32(14).ToString();
            LblRetention.Text = dr.GetInt32(15).ToString();
            LblEffectDate.Text = dr.GetDateTime(16).ToString();
            LblCommission.Text = dr.GetInt32(17).ToString();
            LblPremium.Text = dr.GetInt32(18).ToString();
            LblComments.Text = dr.GetString(19);
            HyperLink1.NavigateUrl = "~/ViewEdit.aspx?ProductId=" + x;
        }

    }
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多