-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();
    }
}
4

2 回答 2

3

不要将 strSQL 作为 CommandText 传递,其中 strSQL 是您在第一个代码块中创建的字符串(我认为...),只需将 SP 名称作为 CommandText 传递,然后将参数添加到您的 sqlcmd 对象。

SqlParameter p = new SqlParameter("@ParameterName", parametervalue));
sqlcmd.Parameters.Add(p);
于 2013-03-13T19:57:42.233 回答
0

只是为了尝试解决您的问题,但请注意这种方法非常危险,不推荐用于 Sql Injection 问题。

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 + "'";

并将命令类型更改为文本。

更好的方法是更改​​ 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);
于 2013-03-13T20:01:58.203 回答