木子屋 Dnawo's BLOG

给SQL 文本命令中的参数传值

👤 dnawo 📅 2008-08-27 👁 7366 👍 0 💬 0 🔄 来源:本站原创
SqlCommand对象的CommandType属性值有三种类型:Text、StoredProcedure和TableDirect,我们都知道,在存储过程中使用参数是非常常见的,因而我们都知道当CommandType值为StoredProcedure时怎么给存储过程参数传值,但是要知道SQL 文本命令中也是可以带参数的,那怎么给他们传值呢?其实两者是一样的,看下边例子:

string Country = "UK";
string City = "London";

using (SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;User ID=sa;Password=sa"))
{
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandTimeout = 60;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "Select count(*) From [Customers] Where Country=@Country And City=@City";
    cmd.Parameters.Add(new SqlParameter("@Country",Country));
    cmd.Parameters.Add(new SqlParameter("@City",City));
    conn.Open();

    Response.Write(cmd.ExecuteScalar());
}

在SQL 事件探查器中看到的结果为:

exec sp_executesql N'Select count(*) From [Customers] Where Country=@Country And City=@City', N'@Country nvarchar(2),@City nvarchar(6)', @Country = N'UK', @City = N'London'

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 轻松加密ASP.NET 2.0 Web程序配置信息 下一篇 → Web.Config中使用特殊字符出错解决方法