Csharp/C Sharp/Database ADO.net/IDbConnection

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Set CommandType and CommandText of IDbConnection

 
using System;
using System.Data;
using System.Data.SqlClient;
class MainClass {
    public static void ExecuteNonQueryExample(IDbConnection con) {
        IDbCommand com = con.CreateCommand();
        com.rumandType = CommandType.Text;
        com.rumandText = "UPDATE Employees SET Title = "Sales Director" WHERE EmployeeId = "5"";
        int result = com.ExecuteNonQuery();
        Console.WriteLine(result);
    }
    public static void ExecuteReaderExample(IDbConnection con) {
        IDbCommand com = con.CreateCommand();
        com.rumandType = CommandType.StoredProcedure;
        com.rumandText = "Ten Most Expensive Products";
        using (IDataReader reader = com.ExecuteReader()) {
            while (reader.Read()) {
                Console.WriteLine("  {0} = {1}", reader["TenMostExpensiveProducts"], reader["UnitPrice"]);
            }
        }
    }
    public static void ExecuteScalarExample(IDbConnection con) {
        IDbCommand com = con.CreateCommand();
        com.rumandType = CommandType.Text;
        com.rumandText = "SELECT COUNT(*) FROM Employees";
        int result = (int)com.ExecuteScalar();
        Console.WriteLine("Employee count = " + result);
    }
    public static void Main() {
        using (SqlConnection con = new SqlConnection()) {
            con.ConnectionString = @"Data Source = .\sqlexpress;Database = Northwind; Integrated Security=SSPI";
            con.Open();
            ExecuteNonQueryExample(con);
            ExecuteReaderExample(con);
            ExecuteScalarExample(con);
        }
    }
}