Latest web development tutorials
 

Web Building - Adding a Database


How to add a database to your web site.


Displaying Data from Database

In a web page, you can easily display data from a database.

You can connect to an existing database, or you can create a new database.


Create a New Database

In this chapter we will demonstrate how to create a new database using WebMatrix:

  • Create a database
  • Add data to the database

Creating a Database

WebMatrix includes an SQL Database design tool.

Follow the instructions below to create an SQL database called "SmallBakery".

Open the Databases workspace and click New Database or Add a database.

WebMatrix will create a database with the same name as your site: "Demo.sdf":

SQL Design

Rename the database to "SmallBakery.sdf".

Click New Table.

Name the new table "Product".

In the new table, create 4 columns named "Id", "Name", "Description", and "Price".

For all columns, set Allows Null to "No".

For the "Id" column, Set Data Type to "bigint", Is Primary Key to "Yes", and Is Identity to "Yes".

For the "Name" and "Description" columns, set Data Type to "nvarchar(50)".

For the "Price" column, set Data Type to "money".

When you are finished, your table design will look like this:

Database

Allow Nulls=No, specifies that the column cannot be blank (empty).

Is Primary Key?, tells the database that this will be the table's primary key.

Is Identity?, tells the database to automatically assign a new Id number for every new record (starting at 1).

Data Type=nvarchar(50), specifies a variable length (max 50) character string data type.

(The n in nvarchar indicates that the character variable can hold international Unicode characters)


Adding Data to the Database

Follow the instructions below to add some data to your database:

Open the Products table (In the left pane, double-click SmallBakery.sdf, double-click Tables, and double-click Products).

Enter the following records:

Name Description Price
Bread Baked fresh every day 2.99
Strawberry Cake Made with organic strawberries 9.99
Apple Pie Second only to your mom's pie 12.99
Pecan Pie If you like pecans, this is for you 10.99
Lemon Pie Made with the best lemons in the world 11.99
Cupcakes Your kids will love these 7.99

After you have finished your input, your screen should look much like this: