本章是关于使用数据库的。
在本章中,我们将:
使用网页,您可以轻松显示数据库中的数据。
您可以连接到现有数据库,或从头开始创建新数据库。
在此示例中,我们将连接到现有的 SQL Server Compact 数据库。
在"DemoWebPages" 文件夹中,创建一个名为"Products.cshtml" 的新 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>
运行示例 »
数据库.打开(姓名) 方法将分两步连接到数据库:
首先,它在应用程序的 App_Data 文件夹中搜索与姓名不带文件扩展名的参数。
如果未找到文件,它将在应用程序的 Web.config 文件中查找 "connection string"。
(连接字符串包含有关如何连接到数据库的信息。它可以包括文件路径或 SQL 数据库的名称以及完整的用户名和密码)
通过这种两步搜索,可以使用本地数据库测试应用程序,并使用连接字符串在 Web 主机上运行应用程序。
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. |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!