2012-02-28 3 views
0

接続文字列でクエリの代わりにストアドプロシージャを使用する方法。あなたは私にコーディングを提案できますか?例を含むストアドプロシージャの使用

+4

*の代わりに、接続文字列での問合せ*私はあなたが接続文字列は、他の目的ではなく、照会のために知っている願っています。実際の質問を定式化するのに時間をかけてください。 – V4Vendetta

答えて

0

sqlコマンド(この場合はストアドプロシージャの呼び出し)を定義してからデータベースに接続し、クエリを送信して結果を受け取る必要があります。

その後、接続を閉じることを忘れないでください!

良いチュートリアルはcsharp-stationでオンラインです。

私はあなたがより詳細な質問がある場合だけで戻ってくると聞いて、ここでは全体の手順を記述することはできません - それはあなたが

string spName = "stored_proc_name"; 
string idParameterValue = "someId"; 

using (SqlConnection connection = new SqlConnection(ConnectionString)) 
{ 
    using (SqlCommand command = new SqlCommand(spName, connection)) 
    { 
     command.CommandType = CommandType.StoredProcedure; 
     command.Parameters.Add(new SqlParameter("@Id", idParameterValue)); 
     connection.Open(); 

     IDbDataAdapter da = new SqlDataAdapter(); 
     da.SelectCommand = command; 

     // (*) Put here a code block of the actual SP execution logic 
     // There are different ways of SP execution and it depends on 
     // return result set type, see below 
    } 
} 

(*)を行くStackOverflowのはここ:)

2

のためにあるものです適切なアプローチを選択:DataSetの設定

  1. 保存出力結果を

    // Store output result set in the DataSet 
    DataSet ds = ExecuteQuery(da); 
    
  2. またはストアドプロシージャの戻り値として単一の整数読んで(ないOUT PARAMを!)場合

    IDataReader reader = command.ExecuteReader(); 
    if (reader != null && reader.Read()) 
    { 
        retValue = (reader.GetInt32(returnParamName)); 
    } 
    
  3. ストアドプロシージャは何も返さない

    bool successfull = cmd.ExecuteNonQuery() == 1; 
    

ヘルパーメソッド

private static DataSet ExecuteQuery(IDataAdapter da) 
{ 
    DataSet ds = new DataSet("rawData"); 
    da.Fill(ds); 

    ds.Tables[0].TableName = "row"; 
    foreach (DataColumn c in ds.Tables[0].Columns) 
    { 
     c.ColumnMapping = MappingType.Attribute; 
    } 

    return ds; 
} 

public static class DataReaderExtensions 
{ 
    public static Int32 GetInt32(this IDataReader rdr, string fieldName) 
    { 
     int ordinal = rdr.GetOrdinal(fieldName); 
     return !rdr.IsDBNull(ordinal) ? rdr.GetInt32(ordinal) : Int32.MinValue; 
    } 
} 

便利なリンク:

+0

「使用中」でラップされているときに接続を閉じる必要はありません –

+0

右を削除します。 – sll

関連する問題