Create Your First ASP.NET Web Service | 2 | WebReference

Create Your First ASP.NET Web Service | 2


Create Your First ASP.NET Web Service [con't]

Integrating the Web Service with a Database

Before we create clients, however, we need to make our service a little bit more sophisticated. Let's add a database. Our service is going to act as a lookup service that users anywhere in the world will use to look up a person's age.

Let's take a look at the database. The name of the database is friends and it has only one table (contacts). Create the table using the following SQL code:

I'm using SQL Server 2008. If you are using any other database system, simply modify the SQL code accordingly. After you run the code, you should have a database called friends that has a table called contacts with some sample data. Now, remove the current Web method and replace it with the following code:

Your entire page should now look like this:

Substitute this line:

...with the appropriate username, password and server name for your connection. This code basically takes a name from the enquiring client and returns the name and age.


A word of caution: using databases in a service like ours does open up the possibility of SQL injection attacks. So, please use some validation if you are going to implement this on a live site. In my next article, we will look at how to access or "consume" our Web service using various clients.

Original: June 23, 2010