2009-11-24 95 views

回答

0

查看connectionstrings.com的連接字符串。

我的一些示例代碼包含在下面。爲清楚起見,刪除了無關的內容和評論。它在C#中,但有很多工具可以將它轉換爲VB。或者你可以通過自己手動轉換來學習另一種激情;-)

GetAllEmployees將返回僱員列表。該列表可以根據需要處理/綁定到您的控件。

public static SqlConnection GetConnection() 
     { 
      //TODO: Use connectionString from app.config file 
      string connString = "Data Source=.\\SQLEXPRESS2008;Initial Catalog=Northwind;Integrated Security=True"; 

      SqlConnection conn = new SqlConnection(connString); 
      return conn; 
     } 


public static List<Employee> GetAllEmployees() 
{ 
    SqlConnection conn = DA.GetConnection(); 

    SqlCommand cmd = new SqlCommand(); 
    cmd.Connection = conn; 
    cmd.CommandText = "SELECT * FROM Employees"; 

    return CreateEmployeeList(cmd); 
} 




private static List<Employee> CreateEmployeeList(SqlCommand cmd) 
{ 
    List<Employee> employees = new List<Employee>(); 

    using (cmd) 
    { 
     cmd.Connection.Open(); 

     SqlDataReader sqlreader = cmd.ExecuteReader(); 

     while (sqlreader.Read()) 
     { 
      Employee employee = new Employee 
       { 
        FirstName = sqlreader["FirstName"].ToString(), 
        LastName = sqlreader["LastName"].ToString(), 
        StreetAddress1 = sqlreader["Address"].ToString(), 
        City = sqlreader["City"].ToString(), 
        Region = sqlreader["Region"].ToString(), 
        PostalCode = sqlreader["PostalCode"].ToString() 
       }; 

      employees.Add(employee); 
     } 
     cmd.Connection.Close(); 
    } 
    return employees; 
}