ASP.NET MVC Framework는 URL을 controller 클래스에 매핑합니다. Controller는 들어오는 요청을 처리하고, 사용자 입력과 상호작용을 다루며, 적당한 응용프로그램 로직을 수행합니다. Controller는 요청에 대한 HTML을 생성하기 위해 view 컴포넌트를 호출합니다.


모든 controller 클래스는 Controller 클래스를 상속받으며 IController, IActionFilter, IDisposable 인터페이스를 구현합니다.


모든 controller는 Controller라고 하는 접미사를 사용해서 이름을 지어야 합니다. 다음 예제를 보면 HomeController라고 되어 있는데요, action 메소드를 포함하고 있으며 view 페이지를 렌더링하기 위한 메소드를 제공합니다.


public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Title"] = "Home Page";
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        ViewData["Title"] = "About Page";

        return View();
    }
}


Action 메소드


MVC Framework를 사용하지 않는 ASP.NET 응용프로그램에서는 사용자와의 상호작용이 페이지를 통해 이루어지지만, ASP.NET MVC 응용프로그램에서는 controller와 action을 통해 이루어집니다. controller 클래스는 action 메소드를 정의하며 원하는 만큼의 action 메소드를 포함할 수 있습니다.


Action 메소드는 보통 사용자와의 상호작용과 1대 1로 매핑이 됩니다. 예를 들면, 브라우저에 URL을 입력하거나 링크를 클릭하거나 폼을 전송하는 것들이 이에 해당됩니다. 이런 동작들은 서버에 대해 요청을 하게 되고 URL은 MVC Framework이 Action을 호출할 수 있는 정보를 포함하게 됩니다.


예를 들어, 사용자가 브라우저에 URL을 입력하면 MVC 응용프로그램은 Global.asax에 정의된 라우팅 규칙을 적용하여 URL을 해석하여 적용할 controller를 결정하고 controller는 수행할 action을 결정합니다.


기본적으로 URL은 controller 다음에 action 이 오는 하위 경로 구조를 하고 있습니다. 예를 들어 URL이 http://contoso.com/MyWebSite/Products/Categories 라면, 하위 경로는 /Products/Categories가 되고 "Products" 가 controller의 이름이며 "Categories" 가 action 의 이름이 됩니다.


만약 URL이 /Products/Detail/5 라고 하면 "Detail" 이 Action이 되고 5 는 Detail Action 메소드에 전달하는 매개변수 값이 될 것입니다.


ActionResult Return Type


모든 action 메소드는 ActionResult 에서 파생된 클래스의 인스턴스를 반환합니다.  모든 action 결과에 대한 base는 ActionResult이지만 action에 따라 여러가지 타입의 action result type이 존재할 수 있습니다.


다음은 내장 action result type입니다.

  • ViewResult : View 메소드에 의해 반환됩니다.
  • RedirectToRouteResult : RedirectToAction 과 RedirectToRoute 메소드에 의해 반환됩니다.
  • RedirectResult : Redirect 메소드에 의해 반환됩니다.
  • ContentResult : Content 메소드에 의해 반환됩니다.
  • JsonResult : Json 메소드에 의해 반환됩니다.
  • EmptyResult : action 메소드가 null을 반환해야 할 경우 반환합니다.

Action 메소드 매개변수


controller 클래스 내에서 URL 매개변수를 참조하는 방법은 여러가지가 있습니다. 기본적으로는 Request와 Response 객체를 사용하여 접근할 수 있습니다.


public void Detail()
{
    int id = Convert.ToInt32(Request["id"]);
}

기존에 사용하던 방법과 크게 다르지 않습니다.


하지만, 좀 더 편리하게 매개변수를 참조할 수 있는 방법이 있습니다.


Action 메소드 매개변수 자동 매핑


ASP.NET MVC Framework는 URL 매개변수 값을 매개변수에 자동으로 연결할 수 있는 방법을 제공하고 있습니다. 이 방법을 사용하게 되면 위에서 살펴보았던 매개변수 값을 받는 문장을 사용하지 않아도 됩니다.


public ResultAction Detail(int id)
{
    ViewData["DetailInfo"] = id;
    return View("Detail");
}

이렇게 하면 매개변수 id에 요청한 내용중 id라는 이름으로 된 값이 자동으로 연결이 됩니다. 별도의 Request 구문을 작성하지 않아도 되는 것이죠.


또한 Query String 대신 매개변수 값을 URL의 일부로 포함시키는 것이 가능해집니다. 예를 들어 /Products/Detail?id=3 와 같은 URL이 있다고 하면, 이 것은 /Products/Detail/3 처럼 바꿀 수 있습니다.

 

기본적인 라우팅 규칙은 /{controller}/{action}/{id} 와 같은 형태를 하고 있습니다. id 에 해당하는 값이 action 메소드의 매개변수로 자동으로 전달이 됩니다.

 

이번 내용은 거의 번역 수준이 되었네요... ^^

Posted by 나비:D
:

ASP.NET에서 MVC(Model-View-Controller) 구현

? Data Column: select for more on pattern organization Application Column: select for more on pattern organization Deployment Column: select for more on pattern organization Infrastructure Column: select for more on pattern organization
Architecture Row: select for more on pattern organization Data Architecture: select for more on pattern organization Application Architecture: select for more on pattern organization Deployment Architecture: select for more on pattern organization Infrastructure Architecture: select for more on pattern organization
Design Row: select for more on pattern organization Data Design: select for more on pattern organization Application Design: select for more on pattern organization Deployment Design: select for more on pattern organization Infrastructure Design: select for more on pattern organization
Implementation Row Data Implementation: select for more on pattern organization Application Implementation: select for more on pattern organization Deployment Implementation: select for more on pattern organization Infrastructure Implementation: select for more on pattern organization
? Complete List of patterns & practices Complete List of patterns & practices Complete List of patterns & practices Complete List of patterns & practices

버전 1.0.1

이 패턴에 대한 공동 작업을 위한 DotDotNet 커뮤니티

patterns & practives 전체 목록 (영문)

상황

Microsoft ASP.NET에서 웹 응용 프로그램을 구축 중인데 응용 프로그램이 복잡하기 때문에 코드 중복을 줄이고 변경 사항이 전파되는 것을 제한하려면 프로그램의 서로 다른 기능을 분리해야 합니다.

구현 전략

소프트웨어의 모델, 뷰 및 컨트롤러 역할을 분리하여 제공된 값 및 ASP.NET에서 MVC(Model-View-Controller)패턴을 구현하는 방법을 설명하기 위해, 다음 예에서는 이 세 역할을 분리하지 않은 단일 페이지 솔루션을 이러한 역할을 분리한 솔루션으로 리팩토링합니다. 이 예제 응용 프로그램은 드롭다운 목록이 있는 단일한 웹 페이지(그림 1)로서, 데이터베이스에 저장되어 있는 기록을 표시합니다.

그림 1: 예제 웹 페이지

사용자는 드롭다운 목록에서 특정 기록을 선택한 다음 전송(Submit) 단추를 클릭합니다. 그러면 응용 프로그램이 데이터베이스의 이 기록에서 모든 트랙의 목록을 검색하여 그 결과를 표로 표시합니다. 이 패턴에 설명된 세 솔루션 모두 정확하게 동일한 기능을 구현합니다.

단일 ASP.NET 페이지

ASP.NET에서 이 페이지를 구현하는 방법은 많습니다. 가장 간단하고 단순한 방법은 다음 코드 예에서 볼 수 있는 것처럼 모든 것을 "Solution.aspx"라고 하는 한 파일에 모두 넣는 방법입니다.

 

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
   <head>
      <title>start</title>
      <script language="c#" runat="server">
         void Page_Load(object sender, System.EventArgs e)
         {
            String selectCmd = "select * from Recording";

            SqlConnection myConnection = 
               new SqlConnection(
                  "server=(local);database=recordings;Trusted_Connection=yes");
            SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, 
               myConnection);

            DataSet ds = new DataSet();
            myCommand.Fill(ds, "Recording");
            
            recordingSelect.DataSource = ds;
            recordingSelect.DataTextField = "title";
            recordingSelect.DataValueField = "id";
            recordingSelect.DataBind();
         }
         
         void SubmitBtn_Click(Object sender, EventArgs e) 
         {   
            String selectCmd = 
               String.Format(
               "select * from Track where recordingId = {0} order by id",
               (string)recordingSelect.SelectedItem.Value);

            SqlConnection myConnection = 
               new SqlConnection(
                  "server=(local);database=recordings;Trusted_Connection=yes");

            SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd,
               myConnection);

            DataSet ds = new DataSet();
            myCommand.Fill(ds, "Track");

            MyDataGrid.DataSource = ds;
            MyDataGrid.DataBind();
         }
      </script>
   </head>
   <body>
      <form id="start" method="post" runat="server">
         <h3>Recordings</h3>
         Select a Recording:<br />
         <asp:dropdownlist id="recordingSelect" runat="server" />
         <asp:button runat="server" text="Submit" OnClick="SubmitBtn_Click" />
         <p/>
         <asp:datagrid id="MyDataGrid" runat="server" width="700" 
               backcolor="#ccccff" bordercolor="black" showfooter="false" 
               cellpadding="3" cellspacing="0" font-name="Verdana" 
               font-size="8pt" headerstyle-backcolor="#aaaadd" 
               enableviewstate="false" />
      </form>
   </body>
</html>
 

이 파일은 이 패턴의 세 역할을 모두 구현하지만 이 역할을 서로 다른 파일이나 클래스로 구분하지는 않습니다. 뷰 역할은 HTML 고유의 렌더링 코드에 의해 표시됩니다. 이 페이지는 바운드 데이터 제어 구현을 사용하여 데이터베이스에서 반환된 DataSet 개체를 표시합니다. 한편 모델 역할은 Page_Load 및 SubmitBtn_Click 함수에서 구현됩니다. 컨트롤러 역할은 직접 표시되지 않으며 ASP.NET에 내재되어 있습니다. 이에 대해서는 페이지 컨트롤러를 참조하십시오. 페이지는 사용자가 요청하면 업데이트됩니다. MVC(Model-View-Controller)는 이것을 수동적인 컨트롤러로 설명합니다. ASP.NET가 컨트롤러 역할을 구현하지만 그 컨트롤러가 응답하는 이벤트에 작업을 연결하는 책임은 프로그래머에게 있기 때문입니다. 이 예에서는 컨트롤러가 Page_Load 함수를 호출하면 페이지가 로드됩니다. 그리고 사용자가 전송(Submit) 단추를 클릭하면 컨트롤러가 SubmitBtn_Click 기능을 호출합니다.

이 페이지는 아주 단순하며 독립적입니다. 이 구현은 유용하며, 응용 프로그램이 작고 자주 변경되지 않는 경우 사용하기 좋습니다. 하지만 개발 중 다음과 같은 상황이 발생하는 경우에는 이 방법을 변경하는 방안을 고려해 보아야 합니다.

  • 병렬 처리를 늘리고 오류 가능성을 줄이고자 할 경우. 뷰 코드와 모델 코드를 서로 다른 사람이 작업하여 병렬 처리 양을 늘리고 오류 발생 가능성을 제한하고자 할 수 있습니다. 예를 들어, 모든 코드가 한 페이지에 있는 경우 개발자는 DataGrid 서식을 변경하고 데이터베이스를 액세스하는 원본 코드 일부를 무심코 변경할 수 있습니다. 하지만 페이지는 다시 보기를 해야만 컴파일되므로 페이지를 다시 보기 전까지는 오류를 발견할 수 없습니다.

  • 여러 페이지에 데이터베이스 액세스 코드를 다시 사용하고자 할 경우. 이 구현에서는 코드를 중복하지 않고는 다른 페이지에 코드를 다시 사용할 수 있는 방법이 없습니다. 중복 코드를 사용하면 데이터베이스 코드가 변경될 경우 그 데이터베이스를 액세스하는 모든 페이지를 수정해야 하므로 유지 관리가 어렵습니다.

    이러한 문제를 처리하기 위해 ASP.NET 구현자들은 코드 비하인드 기능을 도입했습니다.

    코드 비하인드 리팩토링

    Microsoft Visual Studio .NET 개발 시스템의 코드 비하인드 기능을 사용하면 프레젠테이션(뷰) 코드를 모델 컨트롤러 코드에서 쉽게 분리할 수 있습니다. 개별 ASP.NET 페이지에는 그 페이지에서 호출된 메서드가 별도의 클래스에서 구현되도록 하는 메커니즘이 있습니다. 이 메커니즘은 Visual Studio .NET에 의해 활성화되며 Microsoft IntelliSense 기술과 같은 많은 이점이 있습니다. 코드 비하인드 기능을 사용하여 페이지를 구현할 때에는 IntelliSense를 사용하여 해당 페이지 뒤의 코드에서 사용하고 있는 개체의 사용 가능한 메서드 목록을 표시할 수 있습니다. IntelliSense는 .aspx 페이지에서는 작동되지 않습니다.

    다음은 동일한 예로, 이번에는 코드 비하인드 기능을 사용하여 ASP.NET을 구현합니다.

    이 프레젠테이션 코드는 이제 Solution.aspx라고 하는 별도의 파일에 들어 있습니다.

     
    
    <%@ Page language="c#" Codebehind="Solution.aspx.cs" 
       AutoEventWireup="false" Inherits="Solution" %>
    <html>
       <head>
          <title>Solution</title>
       </head>
       <body>
          <form id="Solution" method="post" runat="server">
             <h3>Recordings</h3>
             Select a Recording:<br/>
             <asp:dropdownlist id="recordingSelect" runat="server" />
             <asp:button id="submit" runat="server" text="Submit" 
                enableviewstate="False" />
             <p/>
             <asp:datagrid id="MyDataGrid" runat="server" width="700"
                   backcolor="#ccccff" bordercolor="black" showfooter="false"
                   cellpadding="3" cellspacing="0" font-name="Verdana" font-size="8pt"
                   headerstyle-backcolor="#aaaadd" enableviewstate="false" />
          </form>
       </body>
    </html>
     

    이 코드의 대부분은 첫 번째 구현에서 사용된 코드와 비슷하며 가장 큰 차이점은 첫 번째 줄입니다.

     
    
    <%@ Page language="c#" Codebehind="Solution.aspx.cs" 
       AutoEventWireup="false" Inherits="Solution" %>
     

    이 줄은 코드 비하인드 클래스가 이 페이지에서 참조되는 메서드를 구현하는 ASP.NET 환경을 나타냅니다. 이 페이지에는 데이터베이스를 액세스하는 코드가 없으므로, 데이터베이스가 코드 변경 사항을 액세스하더라도 이 페이지를 수정해야 할 필요가 없습니다. 사용자 인터페이스 디자인에 익숙한 사람은 데이터베이스 액세스 코드에 오류를 유발하지 않고도 이 코드를 수정할 수 있습니다.

    모델 컨트롤러

    이 솔루션의 두 번째 부분은 다음과 같은 코드 비하인드 페이지입니다.

     
    
    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    public class Solution : System.Web.UI.Page
    {
       protected System.Web.UI.WebControls.Button submit;
       protected System.Web.UI.WebControls.DataGrid MyDataGrid;
       protected System.Web.UI.WebControls.DropDownList recordingSelect;
       
       private void Page_Load(object sender, System.EventArgs e)
       {
          if(!IsPostBack)
          {
             String selectCmd = "select * from Recording";
    
             SqlConnection myConnection = 
                new SqlConnection(
                   "server=(local);database=recordings;Trusted_Connection=yes");
             SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
    
             DataSet ds = new DataSet();
             myCommand.Fill(ds, "Recording");
    
             recordingSelect.DataSource = ds;
             recordingSelect.DataTextField = "title";
             recordingSelect.DataValueField = "id";
             recordingSelect.DataBind();
          }
       }
    
       void SubmitBtn_Click(Object sender, EventArgs e) 
       {   
          String selectCmd = 
             String.Format(
             "select * from Track where recordingId = {0} order by id",
             (string)recordingSelect.SelectedItem.Value);
    
          SqlConnection myConnection = 
             new SqlConnection(
                "server=(local);database=recordings;Trusted_Connection=yes");
          SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
    
          DataSet ds = new DataSet();
          myCommand.Fill(ds, "Track");
    
          MyDataGrid.DataSource = ds;
          MyDataGrid.DataBind();
       }
    
       #region Web Form Designer generated code
       override protected void OnInit(EventArgs e)
       {
          //
          // CODEGEN: This call is required by the ASP.NET Web Form Designer.
          //
          InitializeComponent();
          base.OnInit(e);
       }
          
       /// <summary>
       /// Required method for Designer support - do not modify
       /// the contents of this method with the code editor.
       /// </summary>
       private void InitializeComponent()
       {    
          this.submit.Click += new System.EventHandler(this.SubmitBtn_Click);
          this.Load += new System.EventHandler(this.Page_Load);
    
       }
       #endregion
    }
     

    이 코드는 단일 ASP.NET 페이지에서 자체 파일로 옮겨졌습니다. 이 두 엔터티를 하나로 연결하려면 몇몇 구문을 변경해야 합니다. 이 클래스에 정의된 구성원 변수는 Solution.aspx 파일에 참조된 이름과 동일한 이름을 공유합니다. 명시적으로 정의되어야 하는 또 다른 부분은, 이 컨트롤러가 반드시 실행되어야 하는 작업이 발생한 이벤트에 어떻게 연결하는가 입니다. 이 예에서는 InitializeComponent 메서드가 이 두 이벤트를 연결합니다. 첫 번째 이벤트는 Load로, Page_Load 함수로 연결됩니다. 그리고 두 번째 이벤트는 Click으로, 전송(Submit) 단추를 클릭하면 SubmitBtn_Click 함수가 실행되도록 만듭니다.

    코드 비하인드 기능은 뷰 역할을 모델 및 컨트롤러 역할에서 분리하는 훌륭한 메커니즘입니다. 코드 비하인드 기능은 코드 비하인드 클래스에 있는 코드를 다른 페이지에 재사용해야 하는 경우 불충분해질 수 있습니다. 코드 비하인드 페이지에서 코드를 재사용하는 것이 기술적으로는 가능하지만 코드 비하인드 클래스를 공유하는 모든 페이지의 결합이 증가하기 때문에 바람직하지 않습니다.

    MVC(Model-View-Controller) 리팩토링

    마지막 문제를 해결하기 위해서는 컨트롤러에서 모델 코드를 분리해야 합니다. 뷰 코드는 이전 구현에서 사용한 코드와 동일합니다.

    모델

    다음 코드 예는 모델을 표시한 것으로, 데이터베이스에만 의존합니다. 따라서 뷰 의존 코드(ASP.NET 종속성 코드)는 포함되어 있지 않습니다.

     
    
    using System;
    using System.Collections;
    using System.Data;
    using System.Data.SqlClient;
    
    public class DatabaseGateway
    {
       public static DataSet GetRecordings()
       {
          String selectCmd = "select * from Recording";
    
          SqlConnection myConnection = 
             new SqlConnection(
                "server=(local);database=recordings;Trusted_Connection=yes");
          SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
    
          DataSet ds = new DataSet();
          myCommand.Fill(ds, "Recording");
          return ds;
       }
    
       public static DataSet GetTracks(string recordingId)
       {
          String selectCmd = 
             String.Format(
             "select * from Track where recordingId = {0} order by id",
             recordingId);
    
          SqlConnection myConnection = 
             new SqlConnection(
                "server=(local);database=recordings;Trusted_Connection=yes");
          SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
    
          DataSet ds = new DataSet();
          myCommand.Fill(ds, "Track");
          return ds;
       }
     

    이제 이 파일이 데이터베이스에 의존하는 유일한 파일입니다. 이 클래스는 테이블 데이터 게이트웨이의 훌륭한 예입니다. 테이블 데이터 게이트웨이에는 단일 테이블 또는 뷰를 액세스하는 모든 SQL 코드(선택, 삽입, 업데이트, 삭제)가 있습니다. 다른 코드는 이 데이터베이스와의 모든 상호 작용을 위해 자체 메서드를 호출합니다. [Fowler03]

    컨트롤러

    이 리팩토링은 코드 비하인드 기능을 사용하여 그 페이지에 있는 데이터 제어에 모델 코드를 적용하고 컨트롤러가 전달하는 이벤트를 특정 작업 메서드로 매핑합니다. 이 모델은 여기에서 DataSet 개체를 반환하기 때문에 작업이 단순합니다. 이 코드는 뷰 코드와 마찬가지로 데이터베이스에서 데이터가 검색되는 방법에 의존하지 않습니다.

     
    
    using System;
    using System.Data;
    using System.Collections;
    using System.Web.UI.WebControls;
    
    public class Solution : System.Web.UI.Page
    {
       protected System.Web.UI.WebControls.Button submit;
       protected System.Web.UI.WebControls.DataGrid MyDataGrid;
       protected System.Web.UI.WebControls.DropDownList recordingSelect;
       
       private void Page_Load(object sender, System.EventArgs e)
       {
          if(!IsPostBack)
          {
             DataSet ds = DatabaseGateway.GetRecordings();
             recordingSelect.DataSource = ds;
             recordingSelect.DataTextField = "title";
             recordingSelect.DataValueField = "id";
             recordingSelect.DataBind();
          }
       }
    
       void SubmitBtn_Click(Object sender, EventArgs e) 
       {   
          DataSet ds = 
             DatabaseGateway.GetTracks(
             (string)recordingSelect.SelectedItem.Value);
    
          MyDataGrid.DataSource = ds;
          MyDataGrid.DataBind();
       }
    
       #region Web Form Designer generated code
       override protected void OnInit(EventArgs e)
       {
          //
          // CODEGEN: This call is required by the ASP.NET Web Form Designer.
          //
          InitializeComponent();
          base.OnInit(e);
       }
          
       /// <summary>
       /// Required method for Designer support - do not modify
       /// the contents of this method with the code editor.
       /// </summary>
       private void InitializeComponent()
       {    
          this.submit.Click += new System.EventHandler(this.SubmitBtn_Click);
          this.Load += new System.EventHandler(this.Page_Load);
    
       }
       #endregion
    }
     

    테스트

    ASP.NET 환경에서 모델을 분리하면 모델 코드를 테스트하기가 더 쉬워집니다. ASP.NET 환경 내에서 이 코드를 테스트하려면 이 프로세스의 출력을 테스트해야 합니다. 이는, HTML을 읽고 정확한지를 판단해야 하는 것을 의미하는데 그 작업은 아주 지루하고 오류가 발생하기 쉽습니다. 모델을 분리하여 ASP.NET 없이 실행할 수 있게 되면 이러한 지루한 작업을 피할 수 있으며 코드만 분리하여 테스트할 수 있습니다. 다음은 NUnit (http://nunit.org)의 모델 코드 샘플 단위 테스트입니다.

     
    
    using System;
    
    using NUnit.Framework;
    using System.Collections;
    using System.Data;
    using System.Data.SqlClient;
    
    [TestFixture]
    public class GatewayFixture
    {
       [Test]
       public void Tracks1234Query()
       {
    
          DataSet ds = DatabaseGateway.GetTracks("1234");
          Assertion.AssertEquals(10, ds.Tables["Track"].Rows.Count);
       }
    
       [Test]
       public void Tracks2345Query()
       {
          DataSet ds = DatabaseGateway.GetTracks("2345");
          Assertion.AssertEquals(3, ds.Tables["Track"].Rows.Count);
       }
    
       [Test]
       public void Recordings()
       {
          DataSet ds = DatabaseGateway.GetRecordings();
          Assertion.AssertEquals(4, ds.Tables["Recording"].Rows.Count);
    
          DataTable recording = ds.Tables["Recording"];
          Assertion.AssertEquals(4, recording.Rows.Count);
    
          DataRow firstRow = recording.Rows[0];
          string title = (string)firstRow["title"];
          Assertion.AssertEquals("Up", title.Trim());
       }
    }
      

    결과

    ASP.NET에서 MVC를 구현하면 다음과 같은 이점과 단점이 있습니다.

    장점

  • 종속성 감소.ASP.NET 페이지는 프로그래머가 페이지 내에서 메서드를 구현할 수 있도록 해줍니다. 단일 ASP.NET 페이지에서 볼 수 있는 것처럼 이 페이지는 프로토타입 및 작고 수명이 짧은 웹 응용 프로그램에 유용할 수 있습니다. 하지만 페이지가 복잡하고 페이지 간 코드 공유 필요성이 증가하면 코드의 일부를 분리하는 것이 더욱 유용합니다.

  • 코드 중복 감소. DatabaseGateway 클래스의 GetRecordingsGetTracks 메서드를 이제 다른 페이지에서도 사용할 수 있습니다. 따라서 메서드를 여러 뷰로 복사할 필요가 없습니다.

  • 작업 및 문제점 분리. ASP.NET 페이지를 수정하는 데 필요한 기술은 데이터베이스를 액세스하는 코드 작성에 필요한 기술과 다릅니다. 앞서 설명한 것처럼 뷰와 모델을 분리하면 각 분야의 전문가가 동시에 작업할 수 있습니다.

  • 기회의 최적화. 앞서 설명한 것처럼 책임을 특정 클래스로 분리하면 최적화를 위한 기회가 증가됩니다. 앞에서 설명한 예에서, 요청이 있을 때마다 데이터베이스에서 데이터가 로드됩니다. 특정 상황에서 데이터를 캐싱하는 것이 가능하므로 응용 프로그램의 전체적인 성능이 향상될 수 있습니다. 하지만 이는 코드를 분리하지 않으면 어렵거나 불가능합니다.

  • 테스트 가능. 뷰에서 모델을 격리하면 ASP.NET 환경 밖에서 모델을 테스트할 수 있습니다.

    단점

    추가 코드 및 복잡성. 앞에 제시된 예는 더 많은 파일과 코드를 추가하므로 세 역할 모두를 변경해야 할 경우 코드 유지 관리 비용이 높아집니다. 어떤 경우에는 한 파일을 변경하는 것이 변경 사항을 여러 파일로 분리하는 것보다 더 쉬울 수 있습니다. 이 추가 비용은 코드 분리 이유에 불리하게 작용합니다. 작은 응용 프로그램의 경우 이러한 비용을 들일 만한 가치가 없을 수도 있습니다.

    관련 패턴

    자세한 정보는 다음 관련 패턴을 참조하십시오.

  • 테이블 데이터 게이트웨이. 이 패턴은 데이터베이스 테이블에 대해 게이트웨이 역할을 하는 개체입니다. 한 인스턴스가 한 테이블의 모든 역할을 처리합니다. [Fowler03]

  • 바운드 데이터 제어. 이 패턴은 데이터 원본에 바인딩된 사용자 인터페이스 구성 요소로서 화면 또는 페이지에 렌더링할 수 있습니다.

    참고 자료

    [Fowler03] Fowler, Martin. Patterns of Enterprise Application Architecture. Addison-Wesley, 2003.

    Patterns Practices

  • Posted by 나비:D
    :

    원문 : http://www.codemaker.co.uk/it/tips/ado_conn.htm


    MDAC 2.8 다운로드 : http://www.microsoft.com/downloads/details.aspx?displaylang=ko&FamilyID=6c050fe3-c795-4b7d-b037-185d0506396c


    ADO Connection String Samples

    This page contains sample ADO connection strings for ODBC DSN / DSN-Less, OLE DB Providers, Remote Data Services (RDS), MS Remote, and MS DataShape.

    Also included are ADO.NET connection strings for MySQL, ODBC, OLE DB, Oracle, and SQL Server .NET Data Providers.

    These sample connection strings are compiled by Carl Prothman, a Microsoft ASP.NET MVP and Microsoft Certified Professional (MCP)

    If you have an ADO or ADO.NET connection string that is not listed below, or you see an connection string that does not have the correct setting, please send an email to Carl Prothman.  Thanks!


    Table of Contents


    ODBC DSN Connections

    Using an ODBC DSN (Data Source Name) is a two step process.

    1) You must first create the DSN via the "ODBC Data Source Administrator" program found in your computer's Control Panel (or Administrative Tools menu in Windows 2000). Make sure to create a SYSTEM DSN (not a USER DSN) when using ASP. You can also create the DSN via Visual Basic code.

    2) Then use the following connection string - with your own DSN
    name of course.

    oConn.Open "DSN=mySystemDSN;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 
    oConn.Open "FILEDSN=c:\somepath\mydb.dsn;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    For more information, see:  About ODBC data sources and 
    How to Use File DSNs and DSN-less Connections

    Note: The problem with DSN is that Users can (and will) modify or delete them by mistake, then your program won't work so well. So it's better to use a DSN-Less or OLE DB Provider connection string - with a Trusted Connection if possible!


    ODBC DSN-Less Connections

    For Standard Security:

    oConn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=c:\somepath\mydb.mdb;" & _ "Uid=admin;" & _ "Pwd=" 

    If you are using a Workgroup (System database):

    oConn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=c:\somepath\mydb.mdb;" & _ "SystemDB=c:\somepath\mydb.mdw;", _ "myUsername", "myPassword" 

    If want to open up the MDB exclusively

    oConn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=c:\somepath\mydb.mdb;" & _ "Exclusive=1;" & _ "Uid=admin;" & _ "Pwd=" 

    If MDB is located on a Network Share

    oConn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=\\myServer\myShare\myPath\myDb.mdb;" & _ "Uid=admin;" & _ "Pwd=" 

    If MDB is located on a remote machine

    - Or use an XML Web Service via SOAP Toolkit or ASP.NET
    - Or upgrade to SQL Server and use an IP connection string
    - Or use an ADO URL with a remote ASP web page
    - Or use a MS Remote or RDS connection string
      

    If you don't know the path to the MDB (using ASP)

    <% ' ASP server-side code oConn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=" & Server.MapPath(".") & "\myDb.mdb;" & _ "Uid=admin;" & _ "Pwd=" %>

    This assumes the MDB is in the same directory where the ASP page is running. Also make sure this directory has Write permissions for the user account.
     

    If you don't know the path to the MDB (using VB)

    oConn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=" & App.Path & "\myDb.mdb;" & _ "Uid=admin;" & _ "Pwd="

    This assumes the MDB is in the same directory where the application is running.

    For more information, see:  Microsoft Access Driver Programming Considerations

    To view Microsoft KB articles related to Microsoft Access Driver, click here 


    oConn.Open "Driver={Client Access ODBC Driver (32-bit)};" & _ "System=myAS400;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    For more information, see:   A Fast Path to AS/400 Client/Server


    oConn.Open "Driver={Microsoft dBASE Driver (*.dbf)};" & _ "DriverID=277;" & _ "Dbq=c:\somepath"

    Then specify the filename in the SQL statement:

    oRs.Open "Select * From user.dbf", oConn, , ,adCmdText

    Note: MDAC 2.1 (or greater) requires the Borland Database Engine (BDE) to update dBase DBF files. (Q238431).

    For more information, see:  dBASE Driver Programming Considerations

    To view Microsoft KB articles related to Microsoft dBASE Driver, click here 


    oConn.Open "Driver={Microsoft Excel Driver (*.xls)};" & _ "DriverId=790;" & _ "Dbq=c:\somepath\mySpreadsheet.xls;" & _ "DefaultDir=c:\somepath" 

    For more information, see:  Microsoft Excel Driver Programming Considerations

    To view Microsoft KB articles related to Microsoft Excel Driver, click here 


    If using INFORMIX 3.30 ODBC Driver

    oConn.Open "Dsn='';" & _ "Driver={INFORMIX 3.30 32 BIT};" & _ "Host=myHostname;" & _ "Server=myServerName;" & _ "Service=myServiceName;" & _ "Protocol=olsoctcp;" & _ "Database=myDbName;" & _ "UID=myUsername;" & _ "PWD=myPassword" & _ ' Or
    oConn.Open "Dsn=myDsn;" & _ "Host=myHostname;" & _ "Server=myServerName;" & _ "Service=myServiceName;" & _ "Protocol=onsoctcp;" & _ "Database=myDbName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    If using INFORMIX-CLI 2.5 ODBC Driver

    oConn.Open "Driver={Informix-CLI 2.5 (32 Bit)};" & _ "Server=myServerName;" & _ "Database=myDbName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" & _

    For more information, see: Informix Developer ZoneConnection to ODBC Data Source,


    For the local machine

    oConn.Open "Driver={Easysoft IB6 ODBC};" & _ "Server=localhost;" & _ "Database=localhost:C:\Home\Data\Mydb.gdb;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    For a remote machine

    oConn.Open "Driver={Easysoft IB6 ODBC};" & _ "Server=myMachineName;" & _ "Database=myMachineName:C:\Home\Data\Mydb.gdb;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    For more information, see:  Connecting to InterBase and Easysoft


    For the local machine

    oConn.Open "Driver={INTERSOLV InterBase ODBC Driver (*.gdb)};" & _ "Server=localhost;" & _ "Database=localhost:C:\Home\Data\Mydb.gdb;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    For a remote machine

    oConn.Open "Driver={INTERSOLV InterBase ODBC Driver (*.gdb)};" & _ "Server=myMachineName;" & _ "Database=myMachineName:C:\Home\Data\Mydb.gdb;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    For more information, see: Google Search  (if you know a direct URL email me)


    oConn.Open "Driver={Lotus NotesSQL 3.01 (32-bit) ODBC DRIVER (*.nsf)};" & _ "Server=myServerName;" & _ "Database=mydir\myDbName.nsf;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" & _

    For more information, see:   Connection keywords


    To connect to a local database

    oConn.Open "Driver={mySQL};" & _ "Server=MyServerName;" & _ "Option=16834;" & _ "Database=mydb" 

    To connect to a remote database

    oConn.Open "Driver={mySQL};" & _ "Server=db1.database.com;" & _ "Port=3306;" & _ "Option=131072;" & _ "Stmt=;" & _ "Database=mydb;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    For more information, see:  Programs Known to Work with MyODBC


    For the current Oracle ODBC Driver from Microsoft

    oConn.Open "Driver={Microsoft ODBC for Oracle};" & _ "Server=OracleServer.world;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    For the older Oracle ODBC Driver from Microsoft

    oConn.Open "Driver={Microsoft ODBC Driver for Oracle};" & _ "ConnectString=OracleServer.world;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    For more information, see:  Connection String Format and Attributes

    To view Microsoft KB articles related to Microsoft ODBC for Oracle, click here 


    oConn.Open "Driver={Oracle ODBC Driver};" & _ "Dbq=myDBName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    Where:  The DBQ name must be defined in the tnsnames.ora file

    For more information, see:  Oracle8 ODBC Driver Help, Oracle ODBC FAQs, [asporacle] listserv FAQs, and ASPDB Oracle


    oConn.Open "Driver={Microsoft Paradox Driver (*.db )};" & _ "DriverID=538;" & _ "Fil=Paradox 5.X;" & _ "DefaultDir=c:\dbpath\;" & _ "Dbq=c:\dbpath\;" & _ "CollatingSequence=ASCII" 

    Note: MDAC 2.1 (or greater) requires the Borland Database Engine (BDE) to update Paradox ISAM fDBF files. (Q230126).

    Note: There is an extra space after "db" in the Paradox Driver name

    For more information, see:  Paradox Driver Programming Considerations

    To view Microsoft KB articles related to Microsoft Paradox Driver, click here 


    For Standard Security

    oConn.Open "Driver={SQL Server};" & _ "Server=MyServerName;" & _ "Database=myDatabaseName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    For Trusted Connection security

    oConn.Open "Driver={SQL Server};" & _ "Server=MyServerName;" & _ "Database=myDatabaseName;" & _ "Uid=;" & _ "Pwd=" ' Or
    oConn.Open "Driver={SQL Server};" & _ "Server=MyServerName;" & _ "Database=myDatabaseName;" & _ "Trusted_Connection=yes" 

    To Prompt user for username and password

    oConn.Properties("Prompt") = adPromptAlways oConn.Open "Driver={SQL Server};" & _ "Server=MyServerName;" & _ "DataBase=myDatabaseName" 

    To connect to SQL Server running on the same computer

    oConn.Open "Driver={SQL Server};" & _ "Server=(local);" & _ "Database=myDatabaseName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    To connect to SQL Server running on a remote computer (via an IP address)

    oConn.Open "Driver={SQL Server};" & _ "Server=xxx.xxx.xxx.xxx;" & _ "Address=xxx.xxx.xxx.xxx,1433;" & _ "Network=DBMSSOCN;" & _ "Database=myDatabaseName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    Where:
    - xxx.xxx.xxx.xxx is an IP address
    - 1433 is the default port number for SQL Server.
    - "Network=DBMSSOCN" tells ODBC to use TCP/IP rather than Named
       Pipes (Q238949)
     

    For more information, see:  SQLDriverConnect (ODBC)

    To view Microsoft KB articles related to ODBC Driver for SQL Server, click here 


    If using the Sybase System 12 (or 12.5) Enterprise Open Client ODBC Driver

    oConn.Open "Driver={SYBASE ASE ODBC Driver};" & _ "Srvr=myServerName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    If using the Sybase System 11 ODBC Driver

    oConn.Open "Driver={SYBASE SYSTEM 11};" & _ "Srvr=myServerName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    If using the Intersolv 3.10 Sybase ODBC Driver

    oConn.Open "Driver={INTERSOLV 3.10 32-BIT Sybase};" & _ "Srvr=myServerName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    For more information, see: Sybase System 10 ODBC Driver Reference Guide

    To view Microsoft KB articles related to ODBC Driver for Sybase, click here 


    oConn.Open "ODBC; Driver=Sybase SQL Anywhere 5.0;" & _ "DefaultDir=c:\dbpath\;" & _ "Dbf=c:\sqlany50\mydb.db;" & _ "Uid=myUsername;" & _ "Pwd=myPassword;" & _ "Dsn="""""

    Note: Including the DSN tag with a null string is absolutely critical or else you get the dreaded -7778 error.

    For more information, see:  Sybase SQL Anywhere User Guide


    oConn.Open "Provider=Teradata;" & _ "DBCName=MyDbcName;" & _ "Database=MyDatabaseName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    For more information, see  Teradata ODBC Driver


    oConn.Open _ "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _ "Dbq=c:\somepath\;" & _ "Extensions=asc,csv,tab,txt" 

    Then specify the filename in the SQL statement:

    oRs.Open "Select * From customer.csv", _ oConn, adOpenStatic, adLockReadOnly, adCmdText

    Note: If you are using a Tab delimited file, then make sure you create a schema.ini file, and include the "Format=TabDelimited" option.

    For more information, see:  Text File Driver Programming Considerations

    To view Microsoft KB articles related to Microsoft Text Driver, click here 


    With a database container

    oConn.Open "Driver={Microsoft Visual FoxPro Driver};" & _ "SourceType=DBC;" & _ "SourceDB=c:\somepath\mySourceDb.dbc;" & _ "Exclusive=No"  

    Without a database container (Free Table Directory)

    oConn.Open "Driver={Microsoft Visual FoxPro Driver};" & _ "SourceType=DBF;" & _ "SourceDB=c:\somepath\mySourceDbFolder;" & _ "Exclusive=No" 

    For more information, see:  Visual FoxPro ODBC Driver and Q165492

    To view Microsoft KB articles related to ODBC Driver for Visual FoxPro, click here 




    OLE DB Data Link Connections

    For Absolute Path

    oConn.Open "File Name=c:\somepath\myDatabaseName.udl" 

    For Relative Path

    oConn.Open "File Name=myDatabaseName.udl" 

    For more information, see:  HOWTO: Use Data Link Files with ADO

    Note: Windows 2000 no longer contains the "New | Microsoft Data Link" menu  anymore. You can add the Data Link menu back in the menu list by running the "C:\Program Files\Common Files\System\Ole DB\newudl.reg" reg file, then right-click on the desktop and select "New | Microsoft Data
    Link" menu.

    Or you can also create a Data Link file by creating a text file and change it's file extension to ".udl", then double-click the file.

    To view Microsoft KB articles related to Data Link File, click here 




    OLE DB Provider Connections

    oConn.Open "Provider=ADSDSOObject;" & _ "User Id=myUsername;" & _ "Password=myPassword"

    For more information, see:  Microsoft OLE DB Provider for Microsoft Active Directory Service

    To view Microsoft KB articles related to Data Link File, click here 


    oConn.Open "Provider=Advantage OLE DB Provider;" & _ "Data source=c:\myDbfTableDir;" & _ "ServerType=ADS_LOCAL_SERVER;" & _ "TableType=ADS_CDX"

    For more information, see:  Advantage OLE DB Provider (for ADO)


    oConn.Open "Provider=IBMDA400;" & _ "Data source=myAS400;" & _ "User Id=myUsername;" & _ "Password=myPassword"

    For more information, see:   A Fast Path to AS/400 Client/Server


    oConn.Open "Provider=SNAOLEDB;" & _ "Data source=myAS400;" & _ "User Id=myUsername;" & _ "Password=myPassword"

    For more information, see:  Connection and ConnectionString Property

    To view Microsoft KB articles related to OLE DB Provider for AS/400 and VSAM, click here 


    For Data Warehouse

    oConn.Open "Provider=Commerce.DSO.1;" & _ "Data Source=mscop://InProcConn/Server=mySrvName:" & _ "Catalog=DWSchema:Database=myDBname:" & _ "User=myUsername:Password=myPassword:" & _ "FastLoad=True"  ' Or oConn.Open "URL=mscop://InProcConn/Server=myServerName:" & _ "Database=myDBname:Catalog=DWSchema:" & _ "User=myUsername:Password=myPassword:" & _ "FastLoad=True" 

    For Profiling System

    oConn.Open "Provider=Commerce.DSO.1;" & _ "Data Source=mscop://InProcConn/Server=mySrvName:" & _ "Catalog=Profile Definitions:Database=myDBname:" & _ "User=myUsername:Password=myPassword"  ' Or oConn.Open _ "URL=mscop://InProcConnect/Server=myServerName:" & _ "Database=myDBname:Catalog=Profile Definitions:" & _ "User=myUsername:Password=myPassword"

    For more information, see:  OLE DB Provider for Commerce Server, DataWarehouse, and Profiling System

    To view Microsoft KB articles related to OLE DB Provider for Commerce Server, click here 


    For TCP/IP connections

    oConn.Open = "Provider=DB2OLEDB;" & _ "Network Transport Library=TCPIP;" &  _ "Network Address=xxx.xxx.xxx.xxx;" & _ "Initial Catalog=MyCatalog;" & _ "Package Collection=MyPackageCollection;" & _ "Default Schema=MySchema;" & _ "User ID=MyUsername;" & _ "Password=MyPassword" 

    For APPC connections

    oConn.Open = "Provider=DB2OLEDB;" &  _              "APPC Local LU Alias=MyLocalLUAlias;" &  _ "APPC Remote LU Alias=MyRemoteLUAlias;" &  _ "Initial Catalog=MyCatalog;" & _ "Package Collection=MyPackageCollection;" & _ "Default Schema=MySchema;" & _ "User ID=MyUsername;" & _ "Password=MyPassword"

    For more information, see: Connection, ConnectionString Property, and Q218590

    To view Microsoft KB articles related to OLE DB Provider for DB2, click here 


    The Microsoft OLE DB Provider for DTS Packages is a read-only provider that exposes Data Transformation Services Package Data Source Objects.

    oConn.Open = "Provider=DTSPackageDSO;" & _              "Data Source=mydatasource" 

    For more information, see:  OLE DB Providers Tested with SQL Server

    To view Microsoft KB articles related to OLE DB Provider for DTS Packages, click here 


    oConn.Provider = "EXOLEDB.DataSource" oConn.Open = "http://myServerName/myVirtualRootName"

    For more information, see:  Exchange OLE DB ProviderMessaging, Calendaring, Contacts, and Exchange using ADO objects

    To view Microsoft KB articles related to OLE DB Provider for Exchange, click here 


    Actually there is no OLE DB Provider for Excel.  However, you can use the OLE DB Provider for JET to read and write data in Microsoft Excel workbooks. Or you can use the ODBC Driver for Excel.


    oConn.Open "Provider=MSIDXS;" & _ "Data source=MyCatalog"    

    For more information, see: Microsoft OLE DB Provider for Microsoft Indexing Service

    To view Microsoft KB articles related to OLE DB Provider for Index Server, click here 


    oConn.Open "Provider=MSDAIPP.DSO;" & _ "Data Source=http://mywebsite/myDir;" & _ "User Id=myUsername;" & _ "Password=myPassword"

    ' Or

    oConn.Open "URL=http://mywebsite/myDir;" & _ "User Id=myUsername;" & _ "Password=myPassword"

    For more information, see: Microsoft OLE DB Provider for Internet Publishing and  Q245359

    To view Microsoft KB articles related to OLE DB Provider for Internet Publishing, click here 


    For standard security

    oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=c:\somepath\myDb.mdb;" & _ "User Id=admin;" & _ "Password=" 

    If using a Workgroup (System Database)

    oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _            "Data Source=c:\somepath\mydb.mdb;" & _            "Jet OLEDB:System Database=MySystem.mdw", _ "myUsername", "myPassword" 

    Note, remember to convert both the MDB and the MDW to the 4.0
    database format when using the 4.0 OLE DB Provider.
     

    If MDB has a database password

    oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=c:\somepath\mydb.mdb;" & _ "Jet OLEDB:Database Password=MyDbPassword", _ "myUsername", "myPassword" 

    If want to open up the MDB exclusively

    oConn.Mode = adModeShareExclusive oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=c:\somepath\myDb.mdb;" & _ "User Id=admin;" & _ "Password=" 

    If MDB is located on a network share

    oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=\\myServer\myShare\myPath\myDb.mdb" 

    If MDB is located on a remote machine

    - Or use an XML Web Service via SOAP Toolkit or ASP.NET
    - Or upgrade to SQL Server and use an IP connection string
    - Or use an ADO URL with a remote ASP web page
    - Or use a MS Remote or RDS connection string
     

    If you don't know the path to the MDB (using ASP)

    <% ' ASP server-side code oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & Server.MapPath(".") & "\myDb.mdb;" & _ "User Id=admin;" & _ "Password=" %>

    This assumes the MDB is in the same directory where the ASP page is running. Also make sure this directory has Write permissions for the user account.
     

    If you don't know the path to the MDB (using VB)

    oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & App.Path & "\myDb.mdb;" & _ "User Id=admin;" & _ "Password="

    This assumes the MDB is in the same directory where the application is running.

    For more information, see: OLE DB Provider for Microsoft JetQ191754, and Q225048

    Note: Microsoft.Jet.OLEDB.3.51 only gets installed by MDAC 2.0.  Q197902
    Note: MDAC 2.6 and 2.7 do not contain any of the JET components.  Q271908 and Q239114

    To view Microsoft KB articles related to OLE DB Provider for Microsoft JET, click here 


    You can also open an Excel Spreadsheet using the JET OLE DB Provider

    oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=c:\somepath\mySpreadsheet.xls;" & _ "Extended Properties=""Excel 8.0;HDR=Yes""" 

    Where "HDR=Yes" means that there is a header row in the cell range
    (or named range), so the provider will not include the first row of the
    selection into the recordset.  If "HDR=No", then the provider will include
    the first row of the cell range (or named ranged) into the recordset.

    For more information, see:  Q278973

     You can also open a Text file using the JET OLE DB Provider

    oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _  "Data Source=c:\somepath\;" & _  "Extended Properties=""text;HDR=Yes;FMT=Delimited"""

    'Then open a recordset based on a select on the actual file

    oRs.Open "Select * From MyTextFile.txt", oConn, _ adOpenStatic, adLockReadOnly, adCmdText 

    For more information, see:  Q262537

     
    oConn.Open "Provider=Microsoft.Project.OLEDB.9.0;" & _ "Project Name=c:\somepath\myProject.mpp"

    For more information, see:  Microsoft Project 2000 OLE DB Provider Information

    To view Microsoft KB articles related to OLE DB Provider for Microsoft Project, click here 


    oConn.Open "Provider=MySQLProv;" & _ "Data Source=mySQLDB;" & _ "User Id=myUsername;" & _ "Password=myPassword" 

    For more information, see:   API - OLE DB, SWSoft, and Snippet


    WARNING: This OLE DB Provider is considered obsolete by Microsoft

    For Access (Jet)

    oConn.Open "Provider=MSDASQL;" & _ "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=c:\somepath\mydb.mdb;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    For SQL Server

    oConn.Open "Provider=MSDASQL;" & _   "Driver={SQL Server};" & _ "Server=myServerName;" & _ "Database=myDatabaseName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword"

    For more information, see:  Microsoft OLE DB Provider for ODBC

    To view Microsoft KB articles related to OLE DB Provider for ODBC, click here 


    Microsoft OLE DB for Online Analytical Processing (OLAP) is a set of
    objects and interfaces that extends the ability of OLE DB to provide
    access to multidimensional data stores.

    For ADOMD.Catalog

    oCat.ActiveConnection = _ "Provider=MSOLAP;" & _ "Data Source=myOLAPServerName;" & _ "Initial Catalog=myOLAPDatabaseName" 

    For ADOMD.Catalog (with URL)

    oCat.ActiveConnection = _ "Provider=MSOLAP;" & _ "Data Source=http://myServerName/;" & _ "Initial Catalog=myOLAPDatabaseName" 

    For Excel PivotTable

    With ActiveWorkbook.PivotCaches.Add(SourceType:=xlExternal) .Connection = "OLEDB;" & _ "Provider=MSOLAP;" & _ "Location=myServerDataLocation;" & _ "Initial Catalog=myOLAPDatabaseName" .MaintainConnection = True .CreatePivotTable TableDestination:=Range("A1"), _ TableName:= "MyPivotTableName" End With 

    For more information, see:  OLE DB for OLAP, Catalog Object, PivotTable, Connecting Using HTTP

    To view Microsoft KB articles related to OLE DB Provider for OLAP Services, click here 


    oConn.Open "Provider=msdaora;" & _ "Data Source=MyOracleDB;" & _ "User Id=myUsername;" & _ "Password=myPassword"

    For more information, see: Microsoft OLE DB Provider for Oracle

    To view Microsoft KB articles related to OLE DB Provider for Oracle, click here 


    For Standard Security

    oConn.Open "Provider=OraOLEDB.Oracle;" & _ "Data Source=MyOracleDB;" & _ "User Id=myUsername;" & _ "Password=myPassword" 

    For a Trusted Connection

    oConn.Open "Provider=OraOLEDB.Oracle;" & _ "Data Source=MyOracleDB;" & _ "User Id=/;" & _ "Password=" ' Or
    oConn.Open "Provider=OraOLEDB.Oracle;" & _ "Data Source=MyOracleDB;" & _ "OSAuthent=1"

    Note: "Data Source=" must be set to the appropriate Net8 name which is known to the naming method in use. For example, for Local Naming, it is the alias in the tnsnames.ora file; for Oracle Names, it is the Net8 Service Name.

    For more information, see: Oracle Provider for OLE DB Developer's Guide


    oConn.Open "Provider=PervasiveOLEDB;" & _ "Data Source=C:\PervasiveEB" 

    For more information, see:  OLE DB - ADO


    The Microsoft OLE DB Simple Provider (OSP) allows ADO to access any data for which a provider has been written using the OLE DB Simple Provider Toolkit. Simple providers are intended to access data sources that require only fundamental OLE DB support, such as in-memory arrays or XML documents.

    OSP in MDAC 2.6 has been enhanced to support opening hierarchical ADO Recordsets over arbitrary XML files. These XML files may contain the ADO XML persistence schema, but it is not required. This has been implemented by connecting the OSP to the MSXML2.DLL, therefore MSXML2.DLL or newer is required.

    oConn.Open "Provider=MSDAOSP;" & _ "Data Source=MSXML2.DSOControl.2.6" oRS.Open "http://WebServer/VirtualRoot/MyXMLFile.xml",oConn

    For more information, see: Microsoft OLE DB Simple Provider and Q272270

    To view Microsoft KB articles related to OLE DB Provider for Simple Provider, click here 


    oConn.Open "Provider=SQLBaseOLEDB;" & _ "Data source=mySybaseServer;" & _ "Location=mySybaseDB;" & _ "User Id=myUserName;" & _ "Password=myUserPassword"

    For more information, see:  Books on-line   There is a one-time free sign-up,  then select "SQLBase OLE DB Data Provider User's Guide for v7.5 (20-6220-0001)", then download the zip file and extract the document.


    For Standard Security

    oConn.Open "Provider=sqloledb;" & _ "Data Source=myServerName;" & _ "Initial Catalog=myDatabaseName;" & _ "User Id=myUsername;" & _ "Password=myPassword" 

    For a Trusted Connection

    oConn.Open "Provider=sqloledb;" & _ "Data Source=myServerName;" & _ "Initial Catalog=myDatabaseName;" & _ "Integrated Security=SSPI" 

    To connect to a "Named Instance"

    oConn.Open "Provider=sqloledb;" & _ "Data Source=myServerName\myInstanceName;" & _ "Initial Catalog=myDatabaseName;" & _ "User Id=myUsername;" & _ "Password=myPassword"

    Note: In order to connect to a SQL Server 2000 "named instance", you must have MDAC 2.6 (or greater) installed.
     

    To Prompt user for username and password

    oConn.Provider = "sqloledb" oConn.Properties("Prompt") = adPromptAlways oConn.Open "Data Source=myServerName;" & _ "Initial Catalog=myDatabaseName"  

    To connect to SQL Server running on the same computer

    oConn.Open "Provider=sqloledb;" & _ "Data Source=(local);" & _ "Initial Catalog=myDatabaseName;" & _ "User ID=myUsername;" & _ "Password=myPassword" 

    To connect to SQL Server running on a remote computer (via an IP address)

    oConn.Open "Provider=sqloledb;" & _ "Network Library=DBMSSOCN;" & _ "Data Source=xxx.xxx.xxx.xxx,1433;" & _ "Initial Catalog=myDatabaseName;" & _ "User ID=myUsername;" & _ "Password=myPassword"

    Where:
    - "Network Library=DBMSSOCN" tells OLE DB to use TCP/IP rather than
       Named Pipes (Q238949)
    - xxx.xxx.xxx.xxx is an IP address
    - 1433 is the default port number for SQL Server.  Q269882 and Q287932
    - You can also add "Encrypt=yes" for encryption 

    For more information, see: Microsoft OLE DB Provider for SQL Server

    To view Microsoft KB articles related to OLE DB Provider for SQL Server, click here 


    The SQLXMLOLEDB provider is an OLE DB provider that exposes the Microsoft SQLXML functionality through ADO. The SQLXMLOLEDB provider is not a rowset provider; it can only execute commands in the "write to an output stream" mode of ADO.  

    oConn.Open "Provider=SQLXMLOLEDB.3.0;" & _ "Data Provider=SQLOLEDB;" & _ "Data Source=mySqlServerName;" & _ "Initial Catalog=myDatabaseName;" & _ "User Id=myUserName;" & _ "Password=myUserPassword"

    For more information, see:  SQLXML 3.0 and A Survey of Microsoft SQL Server 2000 XML Features

    To view Microsoft KB articles related to OLE DB Provider for SQL Server via SQLXMLOLEDB, click here 


    oConn.Open "Provider=ASAProv;" & _ "Data source=myASA"

    For more information, see:  ASA Programming Interfaces Guide and ASA User's Guide


    oConn.Open "Provider=Sybase ASE OLE DB Provider;" & _ "Data source=myASEServer"
    ' Or
    oConn.Open "Provider=Sybase.ASEOLEDBProvider;" & _ "Srvr=myASEServer,5000;" & _ "Catalog=myDBName;" & _ "User Id=myUserName;" & _ "Password=myUserPassword"

    Where:
    - The Sybase ASE OLE DB provider from the Sybase 12.5 client CD
    - 5000 is the port number for Sybase.

    Note: The Open Client 12 Sybase OLE DB Provider fails to work without creating  a Data Source .IDS file using the Sybase Data Administrator.  These .IDS files resemble ODBC DSNs.

    Note: With Open Client 12.5, the server port number feature finally works, allowing fully qualified network connection strings to be used without defining any .IDS Data Source files.

    For more information, see:  Sybase Advance Search   


    Actually there is no OLE DB Provider for Text files.  However, you can use the OLE DB Provider for JET to read and write data in Text files.  Or you can use the ODBC Driver for Text.


    oConn.Open "Provider=Ardent.UniOLEDB;" & _ "Data source=myServer;" & _ "Location=myDatabase;" & _ "User ID=myUsername;" & _ "Password=myPassword" 

    For more information, see: Ardent Using UniOLEDB 5.1Informix Using UniOLEDB 5.2


    oConn.Open "Provider=vfpoledb;" & _ "Data Source=C:\vfp7\Samples\Data\myVFPDB.dbc;" & _ "Mode=ReadWrite|Share Deny None;" & _ "Collating Sequence=MACHINE;" & _ "Password=''" 

    For more information, see: Microsoft OLE DB Provider for Visual FoxPro

    To view Microsoft KB articles related to OLE DB Provider for Visual FoxPro, click here.

    Note: The Visual FoxPro OLE DB Provider is NOT installed by MDAC 2.x.  You must install Visual FoxPro 7.0 in order to get it's OLE DB Provider.





    Remote Data Service (RDS) Connections

    The following examples show how to connect to a remote database using the RDS Data Control. When using the RDS DataControl's Server/Connect / SQL properties, the RDS DataControl uses the RDS DataFactory on the remote server.  If you use the RDS DataControl's URL property, then the RDS DataFactory is not used at all.

    WARNING:  The RDS DataFactory can be a major security hole if not setup and configured correctly! For more information, see RDS FAQ #24 

    WARNING: RDS is considered obsolete by Microsoft
     

    With the RDS default handler disabled

    With oRdc .Server = "http://myServerName" .Sql = "Select * From Authors Where State = 'CA'" .Connect = "Provider=sqloledb;" & _ "Data Source=(local);" & _ "Initial Catalog=pubs;" & _ "User Id=myUsername;" & _ "Password=myPassword" .Refresh End With 

    With the RDS default handler enabled

    With oRdc .Server = "http://myServerName" .Handler = "MSDFMAP.Handler" .Connect = "Data Source=MyConnectTag;" .Sql = "MySQLTag(""CA"")" .Refresh End With

    The corresponding CONNECT and SQL sections in the default handler \WINNT\MSDFMAP.INI  file would be:

    [connect MyConnectTag] Access = ReadWrite Connect = "Provider=sqloledb; Data Source=(local); Initial Catalog=pubs; User Id=sa; Password="  (put all of this on single line!) [sql MySQLTag] Sql = "Select * From Authors Where State = '?'"

    For more information about the RDS Default Handler, see: Q243245, Q230680, and RDS Customization Handler Microsoft articles

    To view Microsoft KB articles related to RDS, click here 

    To get records from a remote database

    With oRdc .URL = "http://myServerName/AuthorsGet.asp?state=CA" .Refresh End With 

    To save, set the URL property to an ASP web page

    With oRdc .URL = "http://myServerName/AuthorsSave.asp" .SubmitChanges End With
    Note: You must use MDAC 2.5 (or greater) for this feature

    For more information, see:  RDS URL Property

    To view Microsoft KB articles related to RDS, click here 


    MS Remote Provider Connections

    The following connections strings use Microsoft's remote provider  (MS Remote).  The MS Remote provider tells ADO to communicate  with the remote server (via the RDS DataFactory) and to use the  remote provider that is installed on the remote server.

    WARNING:  The RDS DataFactory can be a major security hole if not setup and configured correctly!  For more information, see RDS FAQ #24 

    WARNING: RDS is considered obsolete by Microsoft
     

    If you want to use an ODBC DSN on the remote machine

    oConn.Open "Provider=MS Remote;" & _ "Remote Server=http://myServerName;" & _ "Remote Provider=MSDASQL;" & _ "DSN=AdvWorks;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    If you want to use an OLE DB Provider on the remote machine

    oConn.Open "Provider=MS Remote;" & _ "Remote Server=http://myServerName;" & _ "Remote Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=c:\somepath\mydb.mdb", _ "admin", "" 

    If you want to use an OLE DB Provider on the remote machine

    oConn.Open "Provider=MS Remote;" & _ "Remote Server=http://myServerName;" & _ "Handler=MSDFMAP.Handler;" & _ "Data Source=MyAdvworksConn"

    The corresponding entry in the \winnt\Msdfmap.ini file would be:

    [connect MyAdvworksConn] Access = ReadWrite Connect = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=mydb.mdb; User Id=admin; Password=" (put all of this on single line!)
     

    If you want to use an ODBC DSN on the remote machine

    oConn.Open "Provider=MS Remote;" & _ "Remote Server=http://myServerName;" & _ "Remote Provider=MSDASQL;" & _ "DSN=myDatabaseName;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" 

    If you want to use an OLE DB Provider on the remote machine

    oConn.Open "Provider=MS Remote;" & _ "Remote Server=http://myServerName;" & _ "Remote Provider=SQLOLEDB;" & _ "Data Source=myServerName;" & _ "Initial Catalog=myDatabaseName;" & _ "User ID=myUsername;" & _ "Password=myPassword" 

    If you want to use an OLE DB Provider on the remote machine

    oConn.Open "Provider=MS Remote;" & _ "Remote Server=http://myServerName;" & _ "Handler=MSDFMAP.Handler;" & _ "Data Source=MyPubsConn" 

    The corresponding entry in the \winnt\Msdfmap.ini file would be:

    [connect MyPubsConn] Access = ReadWrite Connect = "Provider=SQLOLEDB; Data Source=myServerName; Initial Catalog=myDatabaseName; User ID=myUsername; Password=myPassword" (put all of this on single line!)

    For more information, see:  Microsoft OLE DB Remoting Provider   and  Q240838

    To view Microsoft KB articles related to MS Remote, click here 
    To view Microsoft KB articles related to RDS, click here 



    ADO URL Connections

    ADO 2.5+ allows you to open up a Recordset based on XML returned from an ASP file over HTTP.  This feature doesn't use RDS at all.

    To get records from a remote database

    oRs.Open "http://myServer/AuthorsGetByState.asp?state=CA",, _ adOpenStatic, adLockBatchOptimistic

    To save changes

    ' Save Recordset into Stream Set oStm = New ADODB.Stream oRs.Save oStm, adPersistXML ' Use MSXML's XMLHTTP object to open ASP Set oXMLHTTP = New MSXML2.XMLHTTP30 oXMLHTTP.Open "POST", "http://myServerName/AuthorsSave.asp" oXMLHTTP.Send oStm.ReadText ' If an error occurred If oXMLHTTP.Status = 500 Then Debug.Print oXMLHTTP.statusText End If

    For more information, see:  ADO Recordset's Open Method




    .NET Data Provider Connections

    The SQL Server .NET Data Provide allows you to connect to a Microsoft SQL Server 7.0 or 2000 databases.  

    For Microsoft SQL Server 6.5 or earlier, use the OLE DB .NET Data Provider with  the "SQL Server OLE DB Provider" (SQLOLEDB).

    Note: The SQL Server .NET Data Provider knows which Provider it is.  Hence the "provider=" part of the connection string is not needed.

    Using C#:

    using System.Data.SqlClient; ... SqlConnection oSQLConn = new SqlConnection(); oSQLConn.ConnectionString = "Data Source=(local);" + "Initial Catalog=mySQLServerDBName;" + "Integrated Security=yes"; oSQLConn.Open(); 

    Using VB.NET:

    Imports System.Data.SqlClient ... Dim oSQLConn As SqlConnection = New SqlConnection() oSQLConn.ConnectionString = "Data Source=(local);" & _ "Initial Catalog=mySQLServerDBName;" & _ "Integrated Security=yes" oSQLConn.Open() 

    If connection to a remote server (via IP address):

    oSQLConn.ConnectionString = "Network Library=DBMSSOCN;" & _ "Data Source=xxx.xxx.xxx.xxx,1433;" & _ "Initial Catalog=mySQLServerDBName;" & _ "User ID=myUsername;" & _ "Password=myPassword"

    Where:
    - "Network Library=DBMSSOCN" tells SqlConnection to use TCP/IP Q238949
    - xxx.xxx.xxx.xxx is an IP address.  
    - 1433 is the default port number for SQL Server.  Q269882 and Q287932
    - You can also add "Encrypt=yes" for encryption 
     

    For more information, see:  System.Data.SQL Namespace, Q308656, and .NET Data Providers

    Note: Microsoft SQLXML Managed Classes exposes the functionality of SQLXML inside the Microsoft .NET Framework.

    To view Microsoft KB articles related to SQLClient, click here 


    The OLE DB .NET Data Provider uses native OLE DB through COM interop to enable data access.  

    To use the OLE DB .NET Data Provider, you must also use an OLE DB provider (e.g.  SQLOLEDB, MSDAORA, or Microsoft.JET.OLEDB.4.0).

    For IBM AS/400 OLE DB Provider

    ' VB.NET Dim oOleDbConnection As OleDb.OleDbConnection Dim sConnString As String = _ "Provider=IBMDA400.DataSource.1;" & _ "Data source=myAS400DbName;" & _ "User Id=myUsername;" & _ "Password=myPassword" oOleDbConnection = New OleDb.OleDbConnection(sConnString) oOleDbConnection.Open() 

    For JET OLE DB Provider

    ' VB.NET Dim oOleDbConnection As OleDb.OleDbConnection Dim sConnString As String = _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:\myPath\myJet.mdb;" & _ "User ID=Admin;" & _ "Password="  oOleDbConnection = New OleDb.OleDbConnection(sConnString) oOleDbConnection.Open() 

    For Oracle OLE DB Provider

    ' VB.NET Dim oOleDbConnection As OleDb.OleDbConnection Dim sConnString As String = _ "Provider=OraOLEDB.Oracle;" & _ "Data Source=MyOracleDB;" & _ "User ID=myUsername;" & _ "Password=myPassword"  oOleDbConnection = New OleDb.OleDbConnection(sConnString) oOleDbConnection.Open() 

    For SQL Server OLE DB Provider

    ' VB.NET Dim oOleDbConnection As OleDb.OleDbConnection Dim sConnString As String = _ "Provider=sqloledb;" & _ "Data Source=myServerName;" & _ "Initial Catalog=myDatabaseName;" & _ "User Id=myUsername;" & _ "Password=myPassword"  oOleDbConnection = New OleDb.OleDbConnection(sConnString) oOleDbConnection.Open() 

    For Sybase ASE OLE DB Provider

    ' VB.NET Dim oOleDbConnection As OleDb.OleDbConnection Dim sConnString As String = _ "Provider=Sybase ASE OLE DB Provider;" & _ "Data Source=MyDataSourceName;" & _ "Server Name=MyServerName;" & _ "Database=MyDatabaseName;" & _ "User ID=myUsername;" & _ "Password=myPassword"  oOleDbConnection = New OleDb.OleDbConnection(sConnString) oOleDbConnection.Open()

    For more information, see:  System.Data.OleDb Namespace and .NET Data Providers

    To view Microsoft KB articles related to OleDbConnection, click here 


    The ODBC .NET Data Provider is an add-on component to the .NET Framework SDK. It provides access to native ODBC drivers the same way the OLE DB .NET Data Provider provides access to native OLE DB providers.

    For SQL Server ODBC Driver

    ' VB.NET Dim oODBCConnection As Odbc.OdbcConnection Dim sConnString As String = _ "Driver={SQL Server};" & _ "Server=MySQLServerName;" & _ "Database=MyDatabaseName;" & _ "Uid=MyUsername;" & _ "Pwd=MyPassword" oODBCConnection = New Odbc.OdbcConnection(sConnString) oODBCConnection.Open() 

    For Oracle ODBC Driver

    ' VB.NET Dim oODBCConnection As Odbc.OdbcConnection Dim sConnString As String = _ "Driver={Microsoft ODBC for Oracle};" & _ "Server=OracleServer.world;" & _ "Uid=myUsername;" & _ "Pwd=myPassword" oODBCConnection = New Odbc.OdbcConnection(sConnString) oODBCConnection.Open() 

    For Access (JET) ODBC Driver

    ' VB.NET Dim oODBCConnection As Odbc.OdbcConnection Dim sConnString As String = _ "Driver={Microsoft Access Driver (*.mdb)};" & _ "Dbq=c:\somepath\mydb.mdb;" & _ "Uid=Admin;" & _ "Pwd=" oODBCConnection = New Odbc.OdbcConnection(sConnString) oODBCConnection.Open() 

    For Sybase System 11 ODBC Driver

    // C# string myConnStr = "Driver={Sybase System 11};" + "SRVR=mySybaseServerName;" + "DB=myDatabaseName;" + "UID=myUsername;" + "PWD=myPassword"; OdbcConnection myConnection = new OdbcConnection(myConnStr); myConnection.Open(); 

    For all other ODBC Drivers

    ' VB.NET Dim oODBCConnection As Odbc.OdbcConnection Dim sConnString As String = "Dsn=myDsn;" & _                       "Uid=myUsername;" & _ "Pwd=myPassword" oODBCConnection = New Odbc.OdbcConnection(sConnString) oODBCConnection.Open()

    For more information, see:  ODBC .Net Data Provider

    To view Microsoft KB articles related to OdbcConnection, click here 


    The .NET Framework Data Provider for Oracle is an add-on component to the .NET Framework that provides access to an Oracle database using the Oracle Call Interface (OCI) as provided by Oracle Client software.  

    Using C#:

    using System.Data.OracleClient; OracleConnection oOracleConn = new OracleConnection(); oOracleConn.ConnectionString = "Data Source=Oracle8i;" + "Integrated Security=yes"; oOracleConn.Open(); 

    Using VB.NET:

    Imports System.Data.OracleClient  Dim oOracleConn As OracleConnection = New OracleConnection() oOracleConn.ConnectionString = "Data Source=Oracle8i;" & _ "Integrated Security=yes"; oOracleConn.Open()

    Note: You must have the Oracle 8i Release 3 (8.1.7) Client or later installed in order for this provider to work correctly.

    Note: You must have the RTM version of the .NET Framework installed in order for this provider to work correctly.

    Note: There are known Oracle 7.3, Oracle 8.0, and Oracle9i client and server problems in this beta release. The server-side issues should be resolved in the final release of the product.  However, Oracle 7.3 client will not be supported.

    For more information, see:   .NET Data Provider for Oracle Beta 1

    To view Microsoft KB articles related to OracleConnection, click here 


    The MySQL .NET Native Provider is an add-on component to the .NET Framework that allows you to access the MySQL database through the native protocol, without going through OLE DB.

    Using C#

    using EID.MySqlClient; MySqlConnection oMySqlConn = new MySqlConnection(); oMySqlConn.ConnectionString = "Data Source=localhost;" + "Database=mySQLDatabase;" + "User ID=myUsername;" + "Password=myPassword;" + "Command Logging=false"; oMySqlConn.Open(); 

    Using VB.NET

    Imports EID.MySqlClient  Dim oMySqlConn As MySqlConnection = New MySqlConnection() oMySqlConn.ConnectionString = "Data Source=localhost;" & _ "Database=mySQLDatabase;" & _ "User ID=myUsername;" & _ "Password=myPassword;" & _ "Command Logging=false" oMySqlConn.Open() 

    For more information, see:   EID's MySQL ADO.NET native provider

    Posted by 나비:D
    :

    BLOG main image
    by 나비:D

    공지사항

    카테고리

    분류 전체보기 (278)
    Programming? (0)
    ---------------------------.. (0)
    나비의삽질 (5)
    Application (177)
    C# (28)
    JAVA (22)
    ASP.NET (3)
    C++ (19)
    C (18)
    .NET (0)
    Visual Basic (12)
    Flex (16)
    Eclipse (8)
    Delphi (16)
    Visual Studio 2005 (5)
    Embed (6)
    Linux (2)
    Mobile (1)
    XML (1)
    안드로이드 (2)
    SQL (51)
    Web (27)
    etc. (14)
    Omnia (0)
    ---------------------------.. (0)

    최근에 올라온 글

    최근에 달린 댓글

    최근에 받은 트랙백

    글 보관함

    달력

    «   2024/04   »
    1 2 3 4 5 6
    7 8 9 10 11 12 13
    14 15 16 17 18 19 20
    21 22 23 24 25 26 27
    28 29 30
    Total :
    Today : Yesterday :