หน้าเว็บ ASP.NET - ฐานข้อมูล
บทนี้เกี่ยวกับการทำงานกับฐานข้อมูล
สิ่งที่เราจะทำ
ในบทนี้เราจะ:
- สร้างเว็บเพจเพื่อแสดงรายการข้อมูลจากฐานข้อมูล
การแสดงข้อมูลจากฐานข้อมูล
ด้วยเว็บเพจ คุณสามารถแสดงข้อมูลจากฐานข้อมูลได้อย่างง่ายดาย
คุณสามารถเชื่อมต่อกับฐานข้อมูลที่มีอยู่ หรือสร้างฐานข้อมูลใหม่ตั้งแต่ต้น
ในตัวอย่างนี้ เราจะเชื่อมต่อกับฐานข้อมูล SQL Server Compact ที่มีอยู่
การเพิ่มหน้าลูกค้า
ในโฟลเดอร์ "DemoWebPages" ให้สร้างไฟล์ CSHTML ใหม่ชื่อ "Products.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 ) method จะเชื่อมต่อกับฐานข้อมูลในสองขั้นตอน:
อันดับแรก จะค้นหาโฟลเดอร์ App_Data ของแอปพลิเคชันสำหรับฐานข้อมูลที่ตรงกับ พารามิเตอร์ ชื่อโดยไม่มีนามสกุลไฟล์
หากไม่พบไฟล์ ระบบจะค้นหา "สตริงการเชื่อมต่อ" ในไฟล์ Web.config ของแอปพลิเคชัน
(สตริงการเชื่อมต่อประกอบด้วยข้อมูลเกี่ยวกับวิธีการเชื่อมต่อกับฐานข้อมูล โดยอาจรวมถึงเส้นทางของไฟล์ หรือชื่อของฐานข้อมูล SQL พร้อมชื่อผู้ใช้และรหัสผ่านแบบเต็ม)
การค้นหาแบบสองขั้นตอนนี้ทำให้สามารถทดสอบแอปพลิเคชันกับฐานข้อมูลภายในเครื่อง และเรียกใช้แอปพลิเคชันบนเว็บโฮสต์โดยใช้สตริงการเชื่อมต่อ
การอ้างอิงวัตถุฐานข้อมูล 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. |