Mega Code Archive

 
Categories / C# / ADO Database
 

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.CommandType = CommandType.Text;         com.CommandText = "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.CommandType = CommandType.StoredProcedure;         com.CommandText = "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.CommandType = CommandType.Text;         com.CommandText = "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);         }     } }