将存储过程作为字符串传递
问题描述:
如何将存储过程与参数一起作为字符串传递给函数?将存储过程作为字符串传递
我想这个代码,但没有运气..
这是业务访问层的代码
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();
}
}
答
传递STRSQL作为的CommandText,其中strSQL是您在第一个代码块(我认为...)中创建的字符串,只需传递SP名称作为CommandText,然后将参数添加到您的sqlcmd对象。
SqlParameter p = new SqlParameter("@ParameterName", parametervalue));
sqlcmd.Parameters.Add(p);
答
只是为了尝试解决你的问题,但是要小心,这种方法是很危险的,不推荐在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);
那么,什么是例外? – 2013-03-13 19:53:16
不要这样做:catch(Exception ex){throw ex; }'。 – Oded 2013-03-13 19:54:09
请阅读[SQL注入](http://en.wikipedia.org/wiki/SQL_injection) - SQL的字符串连接不好。 – Oded 2013-03-13 19:54:47