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 特性會被忽略。 向量的大小可由 Value 型態 SqlVector<T>推斷出。

在 Visual Studio 2010 之前, Prepare 我拋出了一個例外。 從 Visual Studio 2010 開始,此方法不再拋出例外。

適用於