温馨提示×

如何在C#中实现CommandType

小樊
104
2024-07-09 19:47:23
栏目: 编程语言

在C#中,可以通过System.Data.CommandType枚举类型来实现CommandTypeCommandType枚举定义了要在DbCommand对象上执行的命令类型,包括TextStoredProcedureTableDirect等。

下面是一个示例代码,演示如何在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