如何在SqlDataSource SelectCommand中使用变量?
问题描述:
所以用VB创建一个.Net站点并运行MySQL服务器。如何在SqlDataSource SelectCommand中使用变量?
试图在connectionstring
内使用变量来仅检索某些数据。
我目前有头:
<script language="vbscript">
Dim varSQLcommand as String
varSQLcommand = "1"
</script>
和
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:emergency systemsConnectionString3 %>"
ProviderName="<%$ ConnectionStrings:emergency systemsConnectionString3.ProviderName %>"
SelectCommand= "SELECT * from tbldisaster WHERE Disaster_ID = " & varSQLcommand & "" >
</asp:SqlDataSource>
连接字符串要与varSQLcommand = Request.QueryString("ID")
更换varSQLcommand = "1"
,使URL disasterdetails.aspx?ID={1}
。
这是正确的方式来做我想做的事情吗?
答
可以使用SelectParameters
设置自定义变量,在您的SQL:
SelectCommand="SELECT * FROM tblDisaster WHERE Disaster_ID = @Disaster_ID">
<SelectParameters>
<asp:QueryStringParameter QueryStringField="ID" Name="Disaster_ID" />
</SelectParameters>
在这种情况下,过滤条件来自查询字符串(?id=123
),所以我们使用QueryStringParameter
,并将其绑定到参数名称为@Disaster_ID
。然后查询将从网址中提取id值并将其替换为查询中出现的@Disaster_ID
。
答
还有一个问题可以帮助你。你既可以使用SelectParameters作为另一个答复中指出,或者你可以在你的声明这些代码隐藏使用下列内容:
Dim myDisasterID As String = Request.Querystring("id") 'Do whatever you may have to do with the variable SqlDataSource1.SelectParameters.Add("variablename", myDisasterID); SqlDataSource1.SelectCommand = "SELECT * FROM tbldisaster where [email protected]"