在 VB.NET/C# 中使用 SQLParameters






3.44/5 (17投票s)
2004年9月3日
2分钟阅读

259597
在 .NET 中使用 SqlParameters 与存储过程。
引言
当使用 Microsoft Data Access Application Block 访问 Microsoft SQL Server 2000 数据库,并且 CommandType
是存储过程时,可能需要将输入参数传递给存储过程。 本文设置了场景并逐步介绍了成功填充 DataGrid
或 DropDownList
的过程。
如果您不熟悉 Data Access Application Block,您就错过了。 请查看: MSDN。
这应该是每个人 .NET 工具包的一部分,以及其他一些应用程序块,例如异常管理、日志记录应用程序块、缓存应用程序块等。 我有点跑题了。
数据访问
在 VB.NET 或 C# 中,我们都有网页控件或 Windows 控件,它们可以提供从数据库过滤数据的参数。 这些是输入参数。 一个典型的例子可能是从 Web 或 Windows 表单中搜索一些数据项,然后使用结果填充 DataGrid
。
如果我们有三个下拉列表(ddlInputOne
、ddlInputtwo
、ddlInputthree
),它们将为我们的搜索条件(输入参数)提供输入,并且我们正在使用 Microsoft Data Access Application Block,然后填充 DataGrid
(在例程中),将使用以下代码行。(注意:connectionstring
最好隐藏在安全环境中,甚至可以使用集成安全性)。 此外,使用 Ctype
或 Convert
是为了确保类型与存储过程中的类型匹配。
VB.NET
Protected Sub GetResults()
Dim connectionstring as string
connectionstring = "server=MyServer;" & _
"database=MyDatabaseDB;uid=superuser;password=superpwd"
Dim sqlparams(3) as SqlClient.SqlParameter
sqlparams(0) = new SqlClient.SqlParameter("@inputone", SqlDbType.Int)
sqlparams(0).Value = Ctype(ddlInputOne.SelectedItem.Value,Int32)
sqlparams(1) = new SqlClient.SqlParameter("@inputtwo",SqlDbType.TinyInt)
sqlparams(1).Value = Ctype(ddlInputtwo.SelectedItem.Value,Int16)
sqlparams(2) = new SqlClient.SqlParameter("@inputthree",SqlDbType.SmallInt)
sqlparams(2).Value = Ctype(ddlInputthree.SelectedItem.Value,Int16)
dgMyDataGrid.DataSource() = _
Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteReader(connectionstring, _
CommandType.StoredProcedure, "MyStoredProcedure",sqlparams)
dgMyDataGrid.DataBind()
End Sub
C#
protected void Results()
{
string connectionstring = "server=MyServer;database=MyDatabaseDB;" +
"uid=superuser;password=superpwd" ;
SqlClient.SqlParameter sqlparams[3];
sqlparams[0] = new SqlClient.SqlParameter("@inputone", SqlDbType.Int);
sqlparams[0].Value = Convert.ToInt32(ddlInputOne.SelectedItem.Value);
sqlparams[1] = new SqlClient.SqlParameter("@inputtwo",SqlDbType.TinyInt);
sqlparams[1].Value = Convert.ToInt16(ddlInputtwo.SelectedItem.Value);
sqlparams[2] = new SqlClient.SqlParameter("@inputthree",SqlDbType.SmallInt);
sqlparams[2].Value = Convert.ToInt16(ddlInputthree.SelectedItem.Value);
dgMyDataGrid.DataSource() =
Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteReader(connectionstring,
CommandType.StoredProcedure, "MyStoredProcedure",sqlparams);
dgMyDataGrid.DataBind();
}
SQL 参数也可以有不同的语法
C#
SqlParameter[] sqlparams = {
new SqlParameter("@inputone"...),
new SqlParameter("@inputtwo"...),
new SqlParameter("@inputthree"...)
};
VB.NET
sqlparams = SqlParameter() {
new SqlParameter("@inputone"...),
new SqlParameter("@inputtwo"...),
new SqlParameter("@inputthree"...)
}
我希望这能提供信息并展示一些有用的新东西。 我知道我喜欢 Application Blocks 并且经常使用它们。 此代码应该有助于将存储过程与 DAAB 的输入参数一起使用。