SqlCommand.Prepare 方法

定义

在 SQL Server 实例上创建命令的已准备版本。

public:
 override void Prepare();
public override void Prepare();
override this.Prepare : unit -> unit
Public Overrides Sub Prepare ()

示例

下面的示例演示 Prepare 方法的用法。

using System;
using System.Data;
using Microsoft.Data.SqlClient;

namespace SqlCommand_Prepare
{
    class Program
    {
        static void Main()
        {
            string connectionString = "Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)";
            SqlCommandPrepareEx(connectionString);
            Console.ReadLine();

        }
        private static void SqlCommandPrepareEx(string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(null, connection);

                // Create and prepare an SQL statement.
                command.CommandText =
                    "INSERT INTO Region (RegionID, RegionDescription) " +
                    "VALUES (@id, @desc)";
                SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int, 0);
                SqlParameter descParam =
                    new SqlParameter("@desc", SqlDbType.Text, 100);
                idParam.Value = 20;
                descParam.Value = "First Region";
                command.Parameters.Add(idParam);
                command.Parameters.Add(descParam);

                // Call Prepare after setting the Commandtext and Parameters.
                command.Prepare();
                command.ExecuteNonQuery();

                // Change parameter values and call ExecuteNonQuery.
                command.Parameters[0].Value = 21;
                command.Parameters[1].Value = "Second Region";
                command.ExecuteNonQuery();
            }
        }

注解

如果 CommandType 设置为 StoredProcedure,则调用 Prepare 应成功,但可能会导致 no-op。

在调用 Prepare之前,请在要准备的语句中指定要准备的每个参数的数据类型。 对于具有可变长度数据类型的每个参数,必须将属性设置为 Size 所需的最大大小。 Prepare 如果未满足这些条件,则返回错误。

Note

如果通过执行 Transact-SQL USE <database> 语句或调用 ChangeDatabase 方法来更改数据库上下文,则必须 Prepare 再次调用。

如果在调用后调用Execute方法Prepare,则任何大于属性指定的Size值的参数值将自动截断为参数的原始指定大小,并且不会返回截断错误。

输出参数(是否准备好)必须具有用户指定的数据类型。 如果指定除向量以外的可变长度数据类型,则还必须指定最大值 Size

对于矢量数据类型,将 Size 忽略该属性。 矢量的大小是从类型SqlVector<T>推断的Value

在 Visual Studio 2010 之前, Prepare 引发异常。 从 Visual Studio 2010 开始,此方法不会引发异常。

适用于