int Id;
string strConnection;
string strsql;
protected void Page_Load(object sender, EventArgs e)
{ if (!Page.IsPostBack)
{
Id = Convert.ToInt32(this.ClearRequest(Request.QueryString["id"]));
}
} public string GetINFO()
{
strsql="SELECT * FROM infolist where infoid=" + Id;
string strConnection = ConfigurationSettings.AppSettings["dns"];
SqlConnection objConnection = new SqlConnection(strConnection);
objConnection.Open();
SqlCommand cmd = new SqlCommand(strsql, objConnection);
SqlDataReader dr = cmd.ExecuteReader();
string strBody = null;
dr.Read();
if (dr.HasRows)
{
strBody += "" + dr["infotitle"] + "";
}
else
{
strBody += "暂无";
}
dr.Close();
objConnection.Close();
return strBody;
}现在为了安全,拼接字符串太危险,就换成了
strsql="SELECT * FROM infolist where infoid=@Id";但提示,必须声明标量变量 "@Id"。请问这个问题该怎么解决呢?谢谢
string strConnection;
string strsql;
protected void Page_Load(object sender, EventArgs e)
{ if (!Page.IsPostBack)
{
Id = Convert.ToInt32(this.ClearRequest(Request.QueryString["id"]));
}
} public string GetINFO()
{
strsql="SELECT * FROM infolist where infoid=" + Id;
string strConnection = ConfigurationSettings.AppSettings["dns"];
SqlConnection objConnection = new SqlConnection(strConnection);
objConnection.Open();
SqlCommand cmd = new SqlCommand(strsql, objConnection);
SqlDataReader dr = cmd.ExecuteReader();
string strBody = null;
dr.Read();
if (dr.HasRows)
{
strBody += "" + dr["infotitle"] + "";
}
else
{
strBody += "暂无";
}
dr.Close();
objConnection.Close();
return strBody;
}现在为了安全,拼接字符串太危险,就换成了
strsql="SELECT * FROM infolist where infoid=@Id";但提示,必须声明标量变量 "@Id"。请问这个问题该怎么解决呢?谢谢
SqlParameter parm = new SqlParameter(@infoid,null);
parm.Value = Id;
{
strsql="SELECT * FROM infolist where infoid=@ID";
SqlParameter parm = new SqlParameter(@ID,null);
parm.Value = Id;
string strConnection = ConfigurationSettings.AppSettings["dns"];
SqlConnection objConnection = new SqlConnection(strConnection);
objConnection.Open();
SqlCommand cmd = new SqlCommand(strsql, objConnection);
SqlDataReader dr = cmd.ExecuteReader();
string strBody = null;
dr.Read();
if (dr.HasRows)
{
strBody += "" + dr["infotitle"] + "";
}
else
{
strBody += "暂无";
}
dr.Close();
objConnection.Close();
return strBody;
} 我代码修改成了这样,但还是提示
必须声明标量变量 "@ID"。
请高手指导下,不用存储过程
表示查找满足info==@Id条件的元组。在你的语句中,=@Id已经是一个常量了,不再是变量。
可以使用存储过程,这样就可以防止拼接字符串了,以为调用存储过程只需要传递参数,语句如下: SqlCommand comd = new SqlCommand();
comd.CommandType = CommandType.StoredProcedure;
comd.CommandText = "[color=#00FFFF]Proc_select";
comd.Parameters.Add(SqlDbType .VarChar ,10);[/color]
注意:Proc_select 是指实现该功能的存储过程名称
表示查找满足info==@Id条件的元组。在你的语句中,=@Id已经是一个常量了,不再是变量。
可以使用存储过程,这样就可以防止拼接字符串了,以为调用存储过程只需要传递参数,语句如下: SqlCommand comd = new SqlCommand();
comd.CommandType = CommandType.StoredProcedure;
comd.CommandText = "Proc_select";
comd.Parameters.Add(SqlDbType .VarChar ,10);
注意:Proc_select 是指实现该功能的存储过程名称