溫馨提示×

如何在C#中實現CommandType

小樊
145
2024-07-09 19:47:23
欄目: 編程語言

在C#中,可以通過System.Data.CommandType枚舉類型來實現CommandType。CommandType枚舉定義了要在DbCommand對象上執行的命令類型,包括Text、StoredProcedureTableDirect等。

下面是一個示例代碼,演示如何在C#中使用CommandType

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

class Program
{
    static void Main()
    {
        string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            using (SqlCommand command = connection.CreateCommand())
            {
                command.CommandType = CommandType.Text; // 設置命令類型為文本命令
                command.CommandText = "SELECT * FROM Customers";

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine(reader["CustomerName"]);
                    }
                }
            }
        }
    }
}

在上面的示例中,首先創建了一個SqlConnection對象,并打開連接。然后創建一個SqlCommand對象,并設置其CommandTypeText,指定要執行的SQL語句為SELECT * FROM Customers。最后使用ExecuteReader方法執行命令,并通過讀取器SqlDataReader讀取結果集中的數據。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女