CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 409

409

Chương 10: Cơ sở dữ liệu

public static void Main() {

// Tạo đối tượng SqlConnection mới.

using (SqlConnection con = new SqlConnection()) {

// Cấu hình chuỗi kết nối của đối tượng SqlConnection.

con.ConnectionString = "Data Source = localhost;" +

"Database = Northwind; Integrated Security=SSPI";

// Tạo và cấu hình câu lệnh mới có chứa FOR XML AUTO.

SqlCommand com = con.CreateCommand();

com.CommandType = CommandType.Text;

com.CommandText = "SELECT CustomerID, CompanyName" +

" FROM Customers FOR XML AUTO";

// Khai báo XmlReader để nó có thể được tham chiếu trong

// khối finally (bảo đảm đóng nó lại sau khi sử dụng).

XmlReader reader = null;

try {

// Mở kết nối cơ sở dữ liệu.

con.Open();

// Thực thi câu lệnh và lấy XmlReader

// để truy xuất các kết quả.

reader = com.ExecuteXmlReader();

while (reader.Read()) {

Console.Write("Element: " + reader.Name);

if (reader.HasAttributes) {

for (int i = 0; i < reader.AttributeCount; i++) {

reader.MoveToAttribute(i);

Console.Write(" {0}: {1}",

reader.Name, reader.Value);

}