2012-02-28 28 views
0

如何在連接字符串中使用存儲過程而不是查詢。你能建議我編碼嗎?存儲過程使用示例

+4

*而不是查詢在連接字符串*我希望你知道的連接字符串是用於其它目的,而不是查詢。請花一些時間來制定一個實際的問題。 – V4Vendetta 2012-02-28 09:09:33

回答

0

你需要定義你的sql命令 - 在這種情況下調用存儲過程 - 然後連接到數據庫,發送你的查詢並接收結果。

之後不要忘記關閉連接!

一個很好的教程在線csharp-station

我不能在這裏描述整個過程,如果你有更詳細的問題剛回來,問 - 這就是#2是:)

2

在這裏你去

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

(*)選擇一個合適的方法:

  1. 保存輸出結果的數據集設置

    存儲在
  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

不需要關閉連接時,它被封裝在'使用' – 2012-02-28 09:27:48

+0

正確,刪除。 – sll 2012-02-28 09:31:09