2011-04-20 7 views
-1

SqlDataReader를 사용하여 내 scope_identity pk를 쿼리에 대한 다음 페이지의 행 데이터를 가져 오려고하면 "데이터가 없을 때 읽을 수없는 잘못된 시도"라는 오류 메시지가 나타납니다. 이 두 가지 방법 중 하나를 사용하여 처음으로, 그래서 모든 팁 도움이 될 것입니다. 내 코드 :scope_identity 쿼리에서 데이터 판독기 오류가 발생 했습니까?

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(); 
+1

나는 repro 수있는 PC에 아니에요하지만 정체성을 읽을 수있는 당신의 시도는 이상적 * 원래 * 명령의 일부가되어야합니다 (... –

+0

예제에서, 각 명령이 무엇을하는지, 또는'command'가 두 번 실행되는 이유는 명확하지 않습니다 ... –

+1

'SqlCommand'를'using (...)으로 감싸 야합니다. {...}'블록도 있습니다. 다른 모든 것들이 설정되기 전에 연결을 열면 안됩니다. 가능한 한 늦게 열어 다시 닫으십시오. –

답변

0

가 도움이 답변과 제안을 게시 모든 분들께 감사 얻었다 곳에서 URL입니다; 비록 내가 다른 방법을 사용하여 끝났지 만, 도움은 항상 감사하고 있습니다. 그 다른 방식에 관해서, 나는 누군가가 그것을 필요로하는 사람을 따라 왔을 때 (비록 매개 변수화 된 질의가 없어도 아무도 숙제 이상으로 그리고 심지어는 그 이상으로 그것을 필요로하지 않기를 희망하지만) 결국 사용하는 코드를 게시하기로 결정했다.

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; 
     } 

    } 
} 

}

1

에게 보여주지 내보기 페이지에 당신의 삽입 성명의 일부 범위 ID를 사용합니다. 좋아 ...

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

+1

@@ Identity의 범위가 넓어서 데이터베이스가 넓다고 생각하므로 그가 찾고있는 ID를 얻을 수는 없습니다. – Gratzy

+0

예, 맞습니다. –

관련 문제