Trang Web ASP.NET - Cơ sở dữ liệu


Chương này nói về làm việc với cơ sở dữ liệu.


Chúng tôi sẽ làm gì

Trong chương này, chúng ta sẽ:

  • Tạo trang web để liệt kê dữ liệu từ cơ sở dữ liệu

Hiển thị dữ liệu từ cơ sở dữ liệu

Với Trang Web, bạn có thể dễ dàng hiển thị dữ liệu từ cơ sở dữ liệu.

Bạn có thể kết nối với cơ sở dữ liệu hiện có hoặc tạo cơ sở dữ liệu mới từ đầu.

Trong ví dụ này, chúng tôi sẽ kết nối với cơ sở dữ liệu SQL Server Compact hiện có.


Thêm trang khách hàng

Trong thư mục "DemoWebPages", hãy tạo tệp CSHTML mới có tên "Products.cshtml".

Thay thế mã trong tệp bằng mã từ ví dụ bên dưới:

Products.cshtml

@{
var db = Database.Open("SmallBakery"); 
var selectQueryString = "SELECT * FROM Product ORDER BY Name"; 
}

<html> 
<body> 
<h1>Small Bakery Products</h1> 
<table> 
<tr>
<th>Id</th> 
<th>Product</th> 
<th>Description</th> 
<th>Price</th> 
</tr>
@foreach(var row in db.Query(selectQueryString))
{

<tr> 
<td>@row.Id</td> 
<td>@row.Name</td> 
<td>@row.Description</td> 
<td align="right">@row.Price</td> 
</tr> 
}
</table> 
</body> 
</html>

Giải thích ví dụ

Phương thức Database.Open ( name ) sẽ kết nối với cơ sở dữ liệu theo hai bước:

Đầu tiên, nó tìm kiếm trong thư mục App_Data của ứng dụng để tìm cơ sở dữ liệu khớp với tham số tên mà không có phần mở rộng tên tệp.

Nếu không tìm thấy tệp, nó sẽ tìm "chuỗi kết nối" trong tệp Web.config của ứng dụng.

(Chuỗi kết nối chứa thông tin về cách kết nối với cơ sở dữ liệu. Nó có thể bao gồm đường dẫn tệp hoặc tên của cơ sở dữ liệu SQL, với tên người dùng và mật khẩu đầy đủ)

Tìm kiếm hai bước này giúp bạn có thể kiểm tra ứng dụng với cơ sở dữ liệu cục bộ và chạy ứng dụng trên máy chủ web bằng chuỗi kết nối.



Tham chiếu đối tượng cơ sở dữ liệu ASP.NET

Method Description
Database.Execute(SQLstatement [, parameters])Executes SQLstatement (with optional parameters) such as INSERT, DELETE, or UPDATE and returns a count of affected records.
Database.GetLastInsertId() Returns the identity column from the most recently inserted row.
Database.Open(filename)
Database.Open(connectionStringName)
Opens either the specified database file or the database specified using a named connection string from the Web.config file.
Database.OpenConnectionString(connectionString) Opens a database using the connection string. (This contrasts with Database.Open, which uses a connection string name.)
Database.Query(SQLstatement[, parameters])Queries the database using SQLstatement (optionally passing parameters) and returns the results as a collection.
Database.QuerySingle(SQLstatement [, parameters])Executes SQLstatement (with optional parameters) and returns a single record.
Database.QueryValue(SQLstatement [, parameters])Executes SQLstatement (with optional parameters) and returns a single value.