2010-04-13 3 views
2

1)SqlDataReader가 닫힐 때까지 출력 매개 변수를 검색 할 수없는 경우 이유는 무엇입니까? SqlDataReader의 사용되는 동안

는 연관된도록 SqlConnection은 SqlDataReader를 서빙 중이 및 다른 작업은 폐쇄 이외 SqlConnection이 수행 될 수 없다. 이는 SqlDataReader의 Close 메서드가 호출 될 때까지 발생합니다. 예를 들어, Close를 호출 할 때까지는 출력 매개 변수를 검색 할 수 없습니다. 상기 제 true이면

가, 왜 출력 매개 변수의 값을 검색 할 수는 다음 방법은 독자가 폐쇄되기 전에 :

public int Something() 
    { 
     using (SqlConnection con = new SqlConnection(this.ConnectionString)) 
     { 
      SqlCommand cmd = new SqlCommand("some_procedure", con); 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Parameters.Add("@ID", SqlDbType.Int).Direction = ParameterDirection.Output; 
      con.Open(); 
      cmd.ExecuteReader(); 
      return (int)cmd.Parameters["@ID"].Value; 
     } 
    } 

2)

넌 수 CommandText 속성을 다시 설정하고 SqlCommand 개체를 다시 사용하십시오. 그러나 새 명령이나 이전 명령을 실행하려면 먼저 SqlDataReader를 닫아야합니다.

왜 새 명령을 실행하기 전에 sqldatareader를 닫아야합니까? 첫 번째 질문에

고맙습니다

+2

# 1의 경우, 당신은 'SqlDataReader'에 대한 문서를 매우 자세하게 게시하고 있습니다. 아직 사용중인 문서가 아닙니다. 이것은 문서와 모순되지 않으며 적용 할 수 없습니다. –

+1

및 SqlDataReader는 어디에 있습니까? –

+0

젠장 ... 오타 ... 나는 그것을 바로 잡을 것이다 – AspOnMyNet

답변

3

, 당신은 NonQuery을 실행하는 - 그러므로 당신이 출력 매개 변수를 얻기 전에 종료 할 독자가 없습니다.

두 번째 질문의 경우 방금하십시오. 이 명령을 사용하면 다른 사람이 열리는 동안 다른 사람에게 전화를 걸 수 없습니다.

+0

어떻게 연결이 다른 DataReader가 열려 있는지를 "알 수있는"방법을 묻는다. 결코 대답하지 못했다 .. – Earlz

+0

@Earlz - 미안하지만, 나는 모른다. * 어떻게 * 그것을한다. 당신은 Jon Skeet이 필요합니다 :) – cjk

+0

오타를 만들었습니다 ... 편집 된 게시물보기 – AspOnMyNet

0

실례지만, 데이터 판독기 (System.Data.IDataReader)가 무엇인지 명확하게 알 수없는 것 같습니다. 그래서, 내가 보여 보자

using System; 
using System.Data; 
using System.Data.SqlClient; 

string connectionString = "..."; 

// create and open a DB connection: 
using (IDbConnection connection = new SqlConnection(connectionString)) 
{ 
    connection.Open(); 

    // create a command object: 
    using (IDbCommand query = connection.CreateCommand()) 
    { 
     query.CommandType = CommandType.Text; 
     query.CommandText = "SELECT ID, Name, Birthdate FROM SomeTable"; 

     // execute the query and retrieve a data reader object: 
     using (IDataReader reader = query.ExecuteReader()) 
     { 
      // the data reader is now used to read the query result: 
      while (reader.Read()) 
      { 
       int id = reader.GetInt32(0); 
       string name = reader.GetString(1); 
       DateTime birthdate = reader.GetDateTime(0); 
      } 
     } 

     // at this point, the data reader object has been disposed. 
     // the DB connection can now be used again, e.g. by issuing 
     // another query: 

     command.CommandText = "SELECT COUNT(*) FROM SomeOtherTable"; 
     ... 
    } 
} 

참고 : 내가 var을 사용 자제, 그래서 당신은 유형이 포함 정확히 참조하십시오. (SqlConnection과 같은 구체적인 구현 클래스 대신에 대부분 IDbConnection과 같은 인터페이스 유형을 사용하고 있기 때문에 코드를 다른 RDBMS에보다 쉽게 ​​적용 할 수 있습니다.)

코드에서 실제로 데이터 판독기를 사용한 적이 없습니다. 따라서 첫 번째 장소에서 DB 연결을 "차단"할 수있는 열린 데이터 판독기가 없었기 때문에 코드가 작동했습니다.