ASP.NET 웹 페이지 - 데이터베이스
이 장에서는 데이터베이스 작업에 대해 설명합니다.
우리가 할 일
이 장에서 우리는:
- 데이터베이스의 데이터를 나열하는 웹 페이지 만들기
데이터베이스에서 데이터 표시
웹 페이지를 사용하면 데이터베이스의 데이터를 쉽게 표시할 수 있습니다.
기존 데이터베이스에 연결하거나 처음부터 새 데이터베이스를 생성할 수 있습니다.
이 예에서는 기존 SQL Server Compact 데이터베이스에 연결합니다.
고객 페이지 추가
"DemoWebPages" 폴더에서 "Products.cshtml"이라는 새 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>
예시 설명
Database.Open( name ) 메서드는 두 단계로 데이터베이스에 연결합니다.
먼저 응용 프로그램의 App_Data 폴더 에서 파일 이름 확장명이 없는 name 매개변수 와 일치하는 데이터베이스를 검색합니다 .
파일이 없으면 응용 프로그램의 Web.config 파일에서 "연결 문자열"을 찾습니다.
(연결 문자열에는 데이터베이스에 연결하는 방법에 대한 정보가 포함됩니다. 여기에는 전체 사용자 이름과 암호와 함께 파일 경로 또는 SQL 데이터베이스 이름이 포함될 수 있습니다.)
이 2단계 검색을 통해 로컬 데이터베이스로 애플리케이션을 테스트하고 연결 문자열을 사용하여 웹 호스트에서 애플리케이션을 실행할 수 있습니다.
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. |