Write Database-Independent Code - CSharp Database

CSharp examples for Database:Connection

Description

Write Database-Independent Code

Demo Code


using System;//from w ww .j ava2 s .  co  m
using System.Data;
using System.Data.Common;

class MainClass
    {
        public static void Main(string[] args)
        {
            using (DataTable providers = DbProviderFactories.GetFactoryClasses())
            {
                Console.WriteLine("Available ADO.NET Data Providers:");
                foreach (DataRow prov in providers.Rows)
                {
                    Console.WriteLine(" Name:{0}", prov["Name"]);
                    Console.WriteLine("   Description:{0}", prov["Description"]);
                    Console.WriteLine("   Invariant Name:{0}", prov["InvariantName"]);
                }
            }

            DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

            using (IDbConnection con = factory.CreateConnection())
            {
                con.ConnectionString = @"Data Source = .\sqlexpress;" + "Database = Northwind; Integrated Security=SSPI";

                using (IDbCommand com = con.CreateCommand())
                {
                    com.CommandType = CommandType.StoredProcedure;
                    com.CommandText = "Ten Most Expensive Products";

                    con.Open();

                    using (IDataReader reader = com.ExecuteReader())
                    {
                        Console.WriteLine(Environment.NewLine);
                        Console.WriteLine("Price of the Ten Most Expensive Products.");

                        while (reader.Read())
                        {
                            // Display the product details.
                            Console.WriteLine("  {0} = {1}", reader["TenMostExpensiveProducts"], reader["UnitPrice"]);
                        }
                    }
                }
            }
        }
    }

Result


Related Tutorials