Csharp/CSharp Tutorial/ADO.Net/IDbCommand

Материал из .Net Framework эксперт
Версия от 12:19, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Execute Scalar

using System;
using System.Data;
using System.Data.SqlClient;
class MainClass
{
    public static void Main()
    {
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;";
            con.Open();
            // Create and configure a new command.
            IDbCommand com = con.CreateCommand();
            com.rumandType = CommandType.Text;
            com.rumandText = "SELECT COUNT(*) FROM Employee";
    
            // Execute the command and cast the result.
            int result = (int)com.ExecuteScalar();
    
            Console.WriteLine("Employee count = " + result);
        }
    }
}

Update data using SQL update clause

using System;
using System.Data;
using System.Data.SqlClient;
class MainClass
{
    public static void Main()
    {
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;";
            con.Open();
            // Create and configure a new command.
            IDbCommand com = con.CreateCommand();
            com.rumandType = CommandType.Text;
            com.rumandText = "UPDATE Employee SET FirstName = "S"" +
                " WHERE Id = "5"";
    
            // Execute the command and process the result.
            int result = com.ExecuteNonQuery();
    
            if (result == 1)
            {
                Console.WriteLine("Employee title updated.");
            }
            else
            {
                Console.WriteLine("Employee title not updated.");
            }
        }
    }
}