如题,如下代码:请高手详解,小弟不悉丧尽家财,以求正解,谢谢
public int RunProc(string procName)
{
SqlCommand cmd = CreateCommand(procName, null);
cmd.ExecuteNonQuery();
this.Close();
return (int)cmd.Parameters["ReturnValue"].Value;
}
private SqlCommand CreateCommand(string procName, SqlParameter[] prams)
{
// make sure connection is open
Open(); //command = new SqlCommand( sprocName, new SqlConnection( ConfigManager.DALConnectionString ) );
SqlCommand cmd = new SqlCommand(procName, con);
cmd.CommandType = CommandType.StoredProcedure; // add proc parameters
if (prams != null)
{
foreach (SqlParameter parameter in prams)
cmd.Parameters.Add(parameter);
} // return param
cmd.Parameters.Add(
new SqlParameter("ReturnValue", SqlDbType.Int, 4,
ParameterDirection.ReturnValue, false, 0, 0,
string.Empty, DataRowVersion.Default, null)); return cmd;
}
public int RunProc(string procName)
{
SqlCommand cmd = CreateCommand(procName, null);
cmd.ExecuteNonQuery();
this.Close();
return (int)cmd.Parameters["ReturnValue"].Value;
}
private SqlCommand CreateCommand(string procName, SqlParameter[] prams)
{
// make sure connection is open
Open(); //command = new SqlCommand( sprocName, new SqlConnection( ConfigManager.DALConnectionString ) );
SqlCommand cmd = new SqlCommand(procName, con);
cmd.CommandType = CommandType.StoredProcedure; // add proc parameters
if (prams != null)
{
foreach (SqlParameter parameter in prams)
cmd.Parameters.Add(parameter);
} // return param
cmd.Parameters.Add(
new SqlParameter("ReturnValue", SqlDbType.Int, 4,
ParameterDirection.ReturnValue, false, 0, 0,
string.Empty, DataRowVersion.Default, null)); return cmd;
}
cmd.Parameters.Add(new SqlParameter(name,value));
new SqlParameter("@ReturnValue", SqlDbType.Int, 4,
ParameterDirection.ReturnValue, false, 0, 0,
string.Empty, DataRowVersion.Default, null));
new SqlParameter("ReturnValue", SqlDbType.Int, 4,
ParameterDirection.ReturnValue, false, 0, 0,
string.Empty, DataRowVersion.Default, null));
添加存储过程参数,主要是类型,值
CREATE PROCEDURE [Test]
@TableName varchar(50)
as
declare
set nocount on
begin
exec ('Select * From '+@TableName+' Order By id')
end
GO那么 如果你要调用这个存储过程 就得给它传递一个表名
SqlParameter param=null;
param = new SqlParameter("@TableName", tablename);//tablename是程序中传递进来的表名
cmd.Parameter.Add(param);
原来是写个查询字符串
"SELECT * FROM [ApplicationUser] WHERE ApplicationId = " & Request("ApplicationId")
这样,拼凑字符串,会导致SQL注入,如果Request("ApplicationId")输的是特殊字符,那你仔细这条语句就可能出问题了。如果我们写成
"SELECT * FROM [ApplicationUser] WHERE ApplicationId = @ApplicationId"
这样,这个字符串不是拼凑了,前面加@符号的表示一个参数,等于多少?是什么数据类型?我们通过参数来生产
顺便说一下,Add过时了,用AddWithValue更好,你看得是ADO.Net 1.1的书吧?
cmd.Parameters.AddWithValue("@ApplicationId", Request("ApplicationId"))
这样,就给参数赋值了,再执行cmd就可以不用怕SQL注入什么的了,这儿没有确定数据类型,是它会自动确定的,你也可以指定数据类型,像5楼说的,还可以加很多参数
{
cmd.Parameters.AddRange(prams);
}