c#
  • sql-server-2005
  • 2013-03-13 98 views -2 likes 
    -2

    如何將存儲過程與參數一起作爲字符串傳遞給函數?將存儲過程作爲字符串傳遞

    我想這個代碼,但沒有運氣..

    這是業務訪問層的代碼

    try 
    { 
        string Query_string = "SP_InsertOffer_Tab @offer_name ='" + this.offer_name +"', @offer_price = " + this.offer_price + ",@start_date = '" + this.start_date + 
    "',@end_date = '" + this.end_date + "'"; 
    
        int result = DbAcess.Insert_Query(Query_string); 
        return result; 
    } 
    catch (Exception ex) 
    { 
        throw ex; 
    } 
    finally 
    { 
        DbAcess = null; 
    } 
    

    數據庫層的代碼是相反如下

    public int Insert_Query(string strSQL) 
    { 
        SqlConnection con = new SqlConnection(); 
        con = OpenConnection(); 
    
        try 
        { 
         sqlcmd = new SqlCommand(); 
         sqlcmd.Connection = con; 
         sqlcmd.CommandType = CommandType.StoredProcedure; 
         sqlcmd.CommandText = strSQL; 
    
         int Result = sqlcmd.ExecuteNonQuery(); 
         return Result; 
        } 
        catch (Exception ex) 
        { 
         throw ex; 
        } 
        finally 
        { 
         con.Close(); 
        } 
    } 
    
    +3

    那麼,什麼是例外? – 2013-03-13 19:53:16

    +3

    不要這樣做:catch(Exception ex){throw ex; }'。 – Oded 2013-03-13 19:54:09

    +0

    請閱讀[SQL注入](http://en.wikipedia.org/wiki/SQL_injection) - SQL的字符串連接不好。 – Oded 2013-03-13 19:54:47

    回答

    3

    傳遞STRSQL作爲的CommandText,其中strSQL是您在第一個代碼塊(我認爲...)中創建的字符串,只需傳遞SP名稱作爲CommandText,然後將參數添加到您的sqlcmd對象。

    SqlParameter p = new SqlParameter("@ParameterName", parametervalue)); 
    sqlcmd.Parameters.Add(p); 
    
    0

    只是爲了嘗試解決你的問題,但是要小心,這種方法是很危險的,不推薦在SQL注入問題。

    string Query_string = "EXEC SP_InsertOffer_Tab @offer_name ='" + 
          this.offer_name +"', @offer_price = " + 
          this.offer_price + ",@start_date = '" + 
          this.start_date + "',@end_date = '" + this.end_date + "'"; 
    

    並將CommandType更改爲Text。

    更好的方法是改變Insert_Query方法

    public int Insert_Query(string strSQL, SqlParameter[] prm) 
    { 
        using(SqlConnection con = OpenConnection()) 
        { 
         sqlcmd = new SqlCommand(strSql, con); 
         sqlcmd.CommandType = CommandType.StoredProcedure; 
         sqlcmd.Parameters.AddRange(prm) 
         int Result = sqlcmd.ExecuteNonQuery(); 
         return Result; 
        } 
    } 
    

    然後調用它以這種方式

    SqlParameter[] prms = new SqlParameter[] 
    { 
        new SqlParameter("@offer_name", SqlDbType.NVarChar), 
        new SqlParameter("@offer_price", SqlDbType.Money), 
        new SqlParameter("@start_date", SqlDbType.SmallDateTime), 
        new SqlParameter("@end_date", SqlDbType.SmallDateTime) 
    }; 
    prms[0].Value = this.offer_name; 
    prms[1].Value = this.offer_price; 
    prms[2].Value = this.start_date; 
    prms[3].Value = this.end_date; 
    int result = DbAcess.Insert_Query(Query_string, prms); 
    
    相關問題