日期:2009-09-08  浏览次数:20520 次

The following example shows what a simple ADO.NET application that connects to the Northwind database and returns a list of Categories would look like. The example writes the output to the console, or command prompt.<br>

<br>
The following example shows what a simple ADO.NET application that connects to the Northwind database and returns a list of Categories. The example writes the output to the console, or command prompt.<br>
<br>
SqlClient<br>
[Visual Basic]<br>
Imports System<br>
Imports System.Data<br>
Imports System.Data.SqlClient<br>
Imports Microsoft.VisualBasic<br>
<br>
Public Class Sample<br>
<br>
&nbsp;&nbsp;Public Shared Sub Main() <br>
&nbsp;&nbsp;&nbsp;&nbsp;Dim nwindConn As SqlConnection = New SqlConnection(&quot;Data Source=localhost;&quot; & _<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;User Id=sa;Password=pwd;Initial Catalog=northwind&quot;)<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;Dim catCMD As SqlCommand = nwindConn.CreateCommand()<br>
&nbsp;&nbsp;&nbsp;&nbsp;catCMD.CommandText = &quot;SELECT CategoryID, CategoryName FROM Categories&quot;<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;nwindConn.Open()<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;Dim myReader As SqlDataReader = catCMD.ExecuteReader()<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;Do While myReader.Read()<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Console.WriteLine(vbTab & &quot;{0}&quot; & vbTab & &quot;{1}&quot;, myReader.GetInt32(0), myReader.GetString(1))<br>
&nbsp;&nbsp;&nbsp;&nbsp;Loop<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;myReader.Close()<br>
&nbsp;&nbsp;&nbsp;&nbsp;nwindConn.Close()<br>
&nbsp;&nbsp;End Sub<br>
End Class<br>
[C#]<br>
using System;<br>
using System.Data;<br>
using System.Data.SqlClient;<br>
<br>
class Sample<br>
{<br>
&nbsp;&nbsp;public static void Main() <br>
&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;SqlConnection nwindConn = new SqlConnection(&quot;Data Source=localhost;User Id=sa;Password=pwd;Initial Catalog=northwind&quot;);<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;SqlCommand catCMD = nwindConn.CreateCommand();<br>
&nbsp;&nbsp;&nbsp;&nbsp;catCMD.CommandText = &quot;SELECT CategoryID, CategoryName FROM Categories&quot;;<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;nwindConn.Open();<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;SqlDataReader myReader = catCMD.ExecuteReader();<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;while (myReader.Read())<br>
&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs