Webpages Databases in ASP
Sure! Here’s a straightforward introduction to working with databases in ASP.NET Web Pages (WebMatrix style) using the built-in Database helper class.
ASP.NET Web Pages — Working with Databases
1. Connecting to a Database
ASP.NET Web Pages simplifies database access with the Database helper class.
@{ var db = Database.Open("MyConnectionString");}"MyConnectionString"is the name of your connection string defined inweb.config.Supported databases: SQL Server, SQL CE, MySQL, etc.
2. Querying Data
Retrieve data with Query or QuerySingle:
@{ var users = db.Query("SELECT * FROM Users");}<ul>@foreach(var user in users) { <li>@user.Name - @user.Email</li>}</ul>3. Parameterized Queries (Prevent SQL Injection)
@{ string email = "test@example.com"; var user = db.QuerySingle("SELECT * FROM Users WHERE Email = @0", email);}<p>@user.Name</p>4. Inserting Data
@{ int rowsInserted = db.Execute("INSERT INTO Users (Name, Email) VALUES (@0, @1)", "Alice", "alice@example.com");}<p>Inserted @rowsInserted row(s).</p>5. Updating Data
@{ int rowsUpdated = db.Execute("UPDATE Users SET Name = @0 WHERE Id = @1", "Alice Smith", 1);}<p>Updated @rowsUpdated row(s).</p>6. Deleting Data
@{ int rowsDeleted = db.Execute("DELETE FROM Users WHERE Id = @0", 1);}<p>Deleted @rowsDeleted row(s).</p>7. Configuring the Connection String
Add your connection string to web.config:
<connectionStrings> <add name="MyConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyDb;Integrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings>Summary
| Action | Method | Example |
|---|---|---|
| Open DB | Database.Open("name") | var db = Database.Open("MyConnStr"); |
| Select | db.Query("SQL") | var users = db.Query("SELECT * FROM Users"); |
| Select One | db.QuerySingle("SQL", params) | var user = db.QuerySingle("SELECT * FROM Users WHERE Id=@0", 1); |
| Insert/Update/Delete | db.Execute("SQL", params) | db.Execute("INSERT INTO...") |
If you want help with using other databases, migrations, or advanced querying, just let me know!