Csharp/CSharp Tutorial/ADO.Net/DbProviderFactories — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 12:18, 26 мая 2010
Data Provider Factory
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.rumon;
using System.Configuration;
using System.Data;
class Program
{
static void Main(string[] args)
{
string dp = "provider";
string cnStr ="YourProvider";
DbProviderFactory df = DbProviderFactories.GetFactory(dp);
DbConnection cn = df.CreateConnection();
Console.WriteLine(cn.GetType().FullName);
cn.ConnectionString = cnStr;
cn.Open();
DbCommand cmd = df.CreateCommand();
Console.WriteLine("Your command object is a: {0}", cmd.GetType().FullName);
cmd.Connection = cn;
cmd.rumandText = "Select * From Inventory";
DbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Console.WriteLine(dr.GetType().FullName);
while (dr.Read())
Console.WriteLine("-> Car #{0} is a {1}.",dr["CarID"], dr["Make"].ToString().Trim());
dr.Close();
}
}
Get the available data provider factories
using System;
using System.Data;
using System.Data.rumon;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
DataTable tbl = DbProviderFactories.GetFactoryClasses();
foreach (DataRow row in tbl.Rows)
{
Console.WriteLine("{0} ({1})", row["Name"], row["InvariantName"]);
}
}
}
Obtain the DbProviderFactory for SQL Server and create connection from it
using System;
using System.Data;
using System.Data.rumon;
class MainClass
{
public static void Main(string[] args)
{
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
using (IDbConnection con = factory.CreateConnection())
{
con.ConnectionString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;";
using (IDbCommand com = con.CreateCommand())
{
com.rumandType = CommandType.Text;
com.rumandText = "SELECT ID, FirstName FROM Employee";
con.Open();
using (IDataReader reader = com.ExecuteReader())
{
while (reader.Read())
{
// Display the product details.
Console.WriteLine(" {0} = {1}",
reader["ID"],
reader["FirstName"]);
}
}
}
}
}
}