Материал из .Net Framework эксперт
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Connecting to an ODBC Data Source
using System;
using System.Data.Odbc;
class Program
{
static void Main(string[] args)
{
string odbcConnectString = "DRIVER={SQL Server};SERVER=(local);" +
"DATABASE=AdventureWorks;Trusted_Connection=yes;";
string sqlSelect = "SELECT TOP 5 Title, FirstName, LastName FROM Person.Contact";
using (OdbcConnection connection =new OdbcConnection(odbcConnectString))
{
OdbcCommand command = new OdbcCommand(sqlSelect, connection);
connection.Open( );
OdbcDataReader reader = command.ExecuteReader( );
while (reader.Read( ))
Console.WriteLine("{0} {1}", reader[0], reader[1]);
}
}
}
Connecting to a Text File
using System;
using System.Data;
using System.Data.OleDb;
class Program
{
static void Main(string[] args)
{
string connectString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=;Extended Properties=\"text;HDR=yes;FMT=Delimited\";";
OleDbConnection connection = new OleDbConnection(connectString);
connection.Open( );
Console.WriteLine("Connection.String = {0}\n",connectString);
Console.WriteLine("Connection.State = {0}",connection.State);
Console.WriteLine("Connection.Provider = {0}",connection.Provider);
Console.WriteLine("Connection.ServerVersion = {0}",connection.ServerVersion);
connection.Close( );
}
}
Connect to SqlServer using OdbcConnection
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
class Program
{
static void Main(string[] args)
{
string odbcConnectString = "Driver={SQL Native Client};" +
"Server=(local);Database=AdventureWorks;uid=sa;pwd=password;";
using (OdbcConnection connection =new OdbcConnection(odbcConnectString))
{
connection.Open( );
Console.WriteLine("ConnectionString = {0}\n", odbcConnectString);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
}
}
Creating Connection To ODBC
using System;
using System.Data.Odbc;
class MainClass
{
static void Main(string[] args)
{
OdbcConnection MyConnection = new OdbcConnection("DRIVER={MySQL};SERVER=TESTSRV;DATABASE=MyDatabase;UID=root;PWD=\"\"");
MyConnection.Open();
}
}
Odbc Provider
using System;
using System.Data;
using System.Data.Odbc;
class OdbcProvider
{
static void Main(string[] args)
{
string connString = @"dsn=northwindodbc";
string sql = @"select * from employees";
OdbcConnection conn = null;
OdbcDataReader reader = null;
try
{
conn = new OdbcConnection(connString);
conn.Open();
OdbcCommand cmd = new OdbcCommand(sql, conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0} | {1}"
, reader["FirstName"].ToString().PadLeft(10)
, reader[1].ToString().PadLeft(10)
);
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
finally
{
reader.Close();
conn.Close();
}
}
}