2016-10-28 6 views
-1

나는 모두 데이터베이스에서 데이터를 삽입하고 가져 오는 데 주로 사용되는 일반적인 방법을 사용합니다. 하지만 이제는 출력 값이있을 때 db라는 쿼리에서 출력 변수에 의해 반환 된 값을 받아 들여 출력하는 새로운 메서드를 만들어야하는 문제를 발견했습니다. 이런 식으로 사용할 수 있다고 들었습니다.C#을 사용하여 반환 매개 변수가있는 데이터를 얻으려면 어떻게해야합니까?

cmd.Parameters.Add("@new_id", SqlDbType.Int).Direction = ParameterDirection.Output;

하지만 어떻게 내가 일반적인 방법으로이 코드를 변경하지.

내 일반적인 메소드 코드는 다음과 같습니다.

public DataTable GetDataWithParam(string spName, Dictionary<string, string> parms) 
     { 
      try 
      { 
       SqlCommand cmd = new SqlCommand(); 
       cmd.Connection = con; 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.CommandText = spName; 
       foreach (var para in parms) 
       { 
        cmd.Parameters.AddWithValue(para.Key, para.Value); 
       } 

       using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
       { 
        OpenConnection(); 
        DataSet ds = new DataSet(); 
        da.Fill(ds); 
        CloseConnection(); 
        return ds.Tables[0]; 


       } 
      } 
      catch (Exception ex) 
      { 
       ex.Message.ToString(); 
       return null; 
      } 
     } 

출력 변수를 얻으려면 어떻게해야합니까? 도움이 대단히 감사합니다. 또한 db 쿼리에서 반환 값은 int입니다.

+0

'ParameterDirection.Output'을 사용하여 삽입 된 행 ID를 얻을 수 있습니다 (행 ID를 지정한 경우 기본 키로 말할 수 있음) –

답변

0

이 질문을 한 지 몇 주가 지났습니다. 동료들로부터 최상의 솔루션을 찾는데 도움을 얻은 이후로 대답 할 것이라고 생각했습니다. 질문에있는 것과 같은 새로운 일반적인 제네릭 메소드를 만들고 싶지만 출력 결과는 ParameterDirection입니다. 그래서 여기에 내 대답이있다.

public int ExecuteNonQueryWithOutputParamInt(string spName, Dictionary<string, string> parms, Dictionary<string, object> oParam = null) 
     { 
      string key = null; 
      try 
      { 
       SqlCommand cmd = new SqlCommand(); 
       cmd.Connection = con; 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.CommandText = spName; 

       foreach (var para in parms) 
       { 
        cmd.Parameters.AddWithValue(para.Key, para.Value); 
       } 


       if (oParam != null) 
       { 

        foreach (var p in oParam) 
        { 
         cmd.Parameters.AddWithValue(p.Key, p.Value).Direction = ParameterDirection.Output; 
         key = p.Key; 
        } 
       } 
        this.OpenConnection(); 
        cmd.ExecuteNonQuery(); 
        int returnValue = Convert.ToInt32(cmd.Parameters[key].Value); 
        this.CloseConnection(); 
        return returnValue; 


      } 
      catch (Exception ex) 
      { 
       ex.Message.ToString(); 
       return 0; 
      } 
     } 

희망이 하나는 도움이됩니다. 이 도움에 감사드립니다.

+1

'SqlDataAdapter'는 무엇입니까? 코드를 만들었지 만 코드에는 사용되지 않았습니다. –

+0

@AlexanderPetrov 지적 해 주셔서 감사합니다. 'ExecuteNonQuery()'를 사용하기 때문에'SqlDataAdaptor'가 필요 없습니다. –