ASP.NETWebページ-データベース
この章では、データベースの操作について説明します。
何する
この章では、次のことを行います。
- データベースからのデータを一覧表示するWebページを作成します
データベースからのデータの表示
Webページを使用すると、データベースのデータを簡単に表示できます。
既存のデータベースに接続することも、新しいデータベースを最初から作成することもできます。
この例では、既存のSQL ServerCompactデータベースに接続します。
顧客ページの追加
「DemoWebPages」フォルダーに、「Products.cshtml」という名前の新しいCSHTMLファイルを作成します。
ファイル内のコードを以下の例のコードに置き換えます。
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>
例の説明
Database.Open(name)メソッドは、次の2つのステップでデータベースに接続します。
まず、アプリケーションのApp_Dataフォルダーで、ファイル名拡張子のないnameパラメーターに一致するデータベースを検索します。
ファイルが見つからない場合は、アプリケーションのWeb.configファイルで「接続文字列」を探します。
(接続文字列には、データベースへの接続方法に関する情報が含まれています。ファイルパス、または完全なユーザー名とパスワードを含むSQLデータベースの名前を含めることができます)
この2段階の検索により、ローカルデータベースを使用してアプリケーションをテストし、接続文字列を使用してWebホスト上でアプリケーションを実行できます。
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. |