Creating a Parameterized Query in ADO.NET
Page 1 of 1
Expert Donny Mack discusses how to create a parameterized query without using a stored procedure.
Donny Mack is the co-author of Programming Data-Driven Web Applications with ASP.NET (Sams, September 2001, ISBN 0672321068).
Like this article? We recommend
Even though we strongly urge people to always use stored procedures there are times when you just can't. The following demonstrates how to create a parameterized query without the use of a stored procedure.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="c#" runat="Server">
public void Page_Load(Object sender, EventArgs e){
string sSqlCmd = "SELECT * FROM Products WHERE
ProductID = @RecordCount";
SqlConnection SqlCon = new SqlConnection("ser
ver=localhost;uid=sa;pwd=;database=northwind"); SqlCommand SqlCmd = new SqlCommand(sSqlCmd,SqlCon);
SqlCmd.Parameters.Add(new SqlParameter("@RecordCount",
SqlDbType.Int));
SqlCmd.Parameters["@RecordCount"].Value = 7;
SqlCon.Open();
SqlDataReader SqlDr = SqlCmd.ExecuteReader();
Products.DataSource = SqlDr;
Products.DataBind();
SqlCon.Close();
}
</script>
<html>
<body>
<asp:DataGrid id="Products" runat="server" />
</body>
</html>