WebPages Databases

Databases are a core part of web applications, and ASP.NET WebPages provides an easy-to-use API for interacting with databases. You can perform CRUD (Create, Read, Update, Delete) operations using SQL and the built-in database helpers.

Key Topics

Connecting to a Database

Example

@{
    var db = Database.Open("MyDatabase");
}

<p>Database connection established.</p>

Explanation: This example shows how to connect to a database using the Database.Open method. The connection string MyDatabase must be defined in the web.config file.

Querying the Database

Example

@{
    var db = Database.Open("MyDatabase");
    var records = db.Query("SELECT * FROM Users");
}

<h2>User List</h2>
<ul>
    @foreach (var user in records)
    {
        <li>@user.Name (@user.Email)</li>
    }
</ul>

Explanation: The Query method executes a SQL SELECT statement and returns the results as a collection of dynamic objects, which can be iterated over to display user data.

Inserting Data

Example

@{
    var db = Database.Open("MyDatabase");
    db.Execute("INSERT INTO Users (Name, Email) VALUES (@0, @1)", "John Doe", "john@example.com");
}

<p>User added successfully.</p>

Explanation: This example uses the Execute method to insert a new record into the Users table. Parameters are passed securely to prevent SQL injection.

Key Takeaways

  • Use Database.Open to connect to a database defined in the configuration file.
  • The Query and Execute methods are used for retrieving and modifying data, respectively.
  • Always validate and sanitize user input to prevent SQL injection.