Article Options
Recently Viewed
Premium Sponsor
Premium Sponsor

 »  Home  »  Data Programming  »  ADO.NET  »  ADO.NET for Beginners Part Three
ADO.NET for Beginners Part Three
by David Jeavons | Published  01/12/2007 | ADO.NET | Rating:
David Jeavons
I have been programming database applications for almost 12 years starting out with VB3 and using every major version since then. I currently work for a retailer analysis company writing ASP.NET code for our ever evolving web site. I also enjoy helping other programmers with Visual Basic and .NET and am a moderator at vbCity. 

View all articles by David Jeavons...
The Address Book database

Before we start, we will need to create a new database on our SQL Server to work with. The database is called AddressBook and will contain one table with the same basic structure as the Access database used in the previous two articles. At the end of this article is a download link for the AddressBook database file which is compatible with SQL Server 2005. If you download this file then you can simply attach this database to your instance of SQL Server using the SQL Server Management Studio. If you are using SQL Server 2000 or SQL Server Express then the following is the structure of the Contacts table that you will need to create:

 

Field Name Field Type Size
ContactID int  
Title Char 15
FirstName Char 60
LastName Char 60
AddressLine1 Char 75
AddressLine2 Char 75
AddressLine3 Char 75
Town Char 75
County Char 75
Postcode Char 10
Tel_Home Char 25
Tel_Work Char 25
Mobile Char 25
Fax Char 25
Email Char 100

 

The ContactID field should be set as the primary key and also have the Identity (Is Identity for SQL Server 2005) property set to Yes and the Identity Increment and Identity Seed values set to 1.   (They should be at these settings by default).

 

Next we will need to create some stored procedures that will be responsible for managing the database for us. There will be five stored procedures used in this example to retrieve, add, update and delete records from the Contacts table.

 

If you are using the downloaded database then the stored procedures have already been created, otherwise copy the following stored procedure creation statements and run them against the Address Book database. If you are using SQL Server 2000 then this can be done using the Query Analyzer tool, otherwise, use the Management Studio to execute these statements:

 

USE [AddressBook]

GO

 

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

 

CREATE PROCEDURE [dbo].[Contacts_AllContacts_Select]

As

SELECT ContactID, Title, FirstName, LastName, AddressLine1, AddressLine2,

AddressLine3, Town, County, Postcode, Tel_Home, Tel_Work, Mobile, Fax, Email

FROM Contacts

 

GO

 

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

 

CREATE PROCEDURE [dbo].[Contacts_Contact_Select]

@ContactID int

As

SELECT ContactID, Title, FirstName, LastName, AddressLine1, AddressLine2,

AddressLine3, Town, County, Postcode, Tel_Home, Tel_Work, Mobile, Fax, Email

FROM Contacts

WHERE Contacts.ContactID = @ContactID

 

GO

 

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

 

CREATE PROCEDURE [dbo].[Contacts_Delete]

@ContactID int

As

DELETE FROM Contacts WHERE ContactID=@ContactID

 

GO

 

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

 

CREATE PROCEDURE [dbo].[Contacts_Insert]

@Title Char(15),

@FirstName Char(60),

@LastName Char(60)

As

INSERT INTO Contacts (Title, FirstName, LastName)

VALUES

(@Title, @FirstName, @LastName)

 

GO

 

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

 

CREATE PROCEDURE [dbo].[Contacts_Update]

@ContactID int,

@Title Char(15),

@FirstName Char(60),

@LastName Char(60)

As

UPDATE Contacts Set Title=@Title, FirstName=@FirstName, LastName=@LastName

WHERE ContactID=@ContactID

 

Note that the Contacts_Update and Contacts_Insert stored procedures only modify the first three fields in the Contacts table. This is to fit in with the first two articles in only concerning itself with a few of the fields in order to keep this article simple and for you to gain more understanding by adding to these stored procedures if you wish to at a later time.

 

Now that we have the database and stored procedures ready, we can move on to modifying the code that we created in the previous two articles to make use of the SQL Server database. At this point, I highly recommend that you create a copy of this project so that you may compare the differences at a later time.

Comments    Submit Comment

Comment #1  (Posted by an unknown user on 02/15/2007)
Rating
Thanks alot. It's easy for me a chinese to understand what u talk about.
 
Comment #2  (Posted by Resty on 06/21/2007)
Rating
I'm kinda stuck with this tutorial. I did everything & when I ran the program it would point to the line, "adapter.Fill(dt)" and the error would be: ...that the server might not allow remote connections. The fact is the SQL Server is installed locally. Please advise. Cheers!
 
Comment #3  (Posted by David Jeavons on 06/21/2007)
Rating
Hi Resty

What version of SQL Server are you using?

Also, can you post the connection string you are using.


Thanks
 
Comment #4  (Posted by Resty on 06/22/2007)
Rating
Thanks for your urgent reply. I'm actually using the SQL Server 2005 Express Edition & I'm doing my project in VB 2005 Express Edition. Below is a bit of my code which have the connection string:

Private Sub RetrieveContacts()
Dim conn As New SqlConnection("Data Source=(Local);Initial Catalog=AddressBook;Integrated Security=SSPI")
Dim adapter As New SqlDataAdapter("Contacts_AllContacts_Select", conn)
Dim dt As New DataTable("Contacts")
Try
adapter.Fill(dt)

Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

dgContacts.DataSource = dt

End Sub

Hoping for your next reply. Cheers

Resty

 
Comment #5  (Posted by David Jeavons on 06/22/2007)
Rating
Hi Resty

I am not sure that the connection string you are using will work with SQL Server 2005 Express Edition. Instead, you might like to try one of the following:

If you are storing your database in the Data directory then:

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;

Otherwise, if your database resides somewhere on your machine:

Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;

Hopefully one of these connection strings will resolve your issue.


HTH
 
Comment #6  (Posted by Resty on 06/22/2007)
Rating
Connection now works, but I have another problem. When adding some records & actually saving them, then closing the program & coming back to it again, the data are lost. That also goes with edit & delete function. When program closes, it returns to its original state. What is happening this time?
Please shed light on this. Cheers!


 
Comment #7  (Posted by David Jeavons on 06/22/2007)
Rating
Hi Resty

I think what is happening is that your database file has the property "Copy to Output Directory" set to "Copy Always". This means that each time you build (debug) your application the database file is copied to your output directory and you are then using this database during the lifetime of the application. The next time you run your program this database is overwritten therefore giving the impression that data is not being saved.

You can change this property value to "Do Not Copy" thus ensuring that you are always working with the same database file.


HTH
 
Comment #8  (Posted by Resty on 06/25/2007)
Rating
Thanks David! It's working perfectly now. Looking forward to more articles like this one from you. Really a great tutorial to learn programming!!!
 
Comment #9  (Posted by an unknown user on 07/03/2007)
Rating
Exactly what I was looking for. Most tutorials target design database manipulation techniques instead of programatic techniques.
Fantastic tutorial.
 
Comment #10  (Posted by an unknown user on 10/26/2007)
Rating
Outstanding. Just outstanding for me, a beginner. Outstanding. Thanks much.
 
Comment #11  (Posted by an unknown user on 11/14/2007)
Rating
Straight forward tutorial, exactly what the novice needs.
 
Comment #12  (Posted by an unknown user on 12/27/2007)
Rating
Very good job a explaining how to create a database project for access and SQLServer.
 
Comment #13  (Posted by Steve on 01/14/2008)
Rating
Thank you very much for taking the time and effort to write a superb set of tutorials - I have learned more in the last 3 nights than in the previous 3 months!
Question - in SQL databases, what is the difference between "Do not copy", "Copy if Newer", and "Copy Always".
Again thank you.
Steve
 
Comment #14  (Posted by David Jeavons on 01/15/2008)
Rating
Hi Steve

Thank you for your comments.

To answer your question, the "Do not copy" will ensure that when you compile your application, the database will not be copied to the output (build) directory. The "Copy if Newer" will only copy the file to the output directory if the file is newer. However, be careful with this option as when you compile your application the date of the file may change in which case the file will be copied even if the contents have not changed. Finally the "Copy Always" option will always copy the file to the output directory.

I personally find it safer to use the "Do not copy" option and ensure that I manually copy the database file. Thus ensuring that no changes are overwritten by mistake.


HTH
 
Comment #15  (Posted by an unknown user on 02/14/2008)
Rating
Great article!
 
Comment #16  (Posted by an unknown user on 02/23/2008)
Rating
Super!!!
 
Comment #17  (Posted by Fan on 08/11/2008)
Rating
Hi David

"I am not sure that the connection string you are using will work with SQL Server 2005 Express Edition. Instead, you might like to try one of the following:

If you are storing your database in the Data directory then:

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;

Otherwise, if your database resides somewhere on your machine:

Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;

Hopefully one of these connection strings will resolve your issue."

About what you written above, the

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;

is to paste at where?
 
Comment #18  (Posted by Fan on 08/11/2008)
Rating
I have another question, what if I want to create the store procedure, how to I create one? Copy the codes to where?

I am using VB 2008 Express edition with SQL Server 2005 Express Edition.
 
Comment #19  (Posted by David Jeavons on 08/12/2008)
Rating
Hi Fan

To create the stored procedures you can either use the SQL Server Management Studio Express and create a new query (make sure you have selected your Address Book database for the target of the query, note that this may also need attaching first) and then paste the stored procedure code into the query window and execute the query.

Alternatively, you can use the Server Explorer within Visual Studio to connect to your database and then right click on the database and select Create New Stored Procedure. For this approach however you will need to create each one individually.

Thanks for the info on the connection strings, however I did test my connection string against an SQL Server 2005 Express database so I am pretty confident that it works.


HTH
 
Comment #20  (Posted by Fan on 08/12/2008)
Rating
I recieved such error :

"An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL server)"

What went wrong? Sorry for giving you troubles..
 
Comment #21  (Posted by David Jeavons on 08/13/2008)
Rating
Hi Fan

What connection string are you currently using?

Did you resolve your issue regarding how to create stored procedures?
 
Comment #22  (Posted by Fan on 08/17/2008)
Rating
I still not sure how to create the stored procedures.

The connection string I used is same as yours. I do change the source according to the directory of the database. But still the same.
 
Comment #23  (Posted by an unknown user on 12/01/2008)
Rating
cochitr
 
Comment #24  (Posted by an unknown user on 01/03/2009)
Rating
Well done, clear, very useful in my work.
 
Comment #25  (Posted by an unknown user on 02/07/2009)
Rating
I have encountered some problems when I attemp to modify or delete an existing register, I Created A DBase ("Matricula"), and a table("Materias"), and I get a run time error and the cursor stops on the TableAdapterManager.UpdateAll Line, of the BindingNavigatorSaveItem_Click procedure:
Private Sub MateriasBindingNavigatorSaveItem_Click(ByVal Sender As SystemObject ...
Me.Validate
Me.MateriasBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Matricula) '<-- Error at this line, the Cursor Stop Here
End Sub

The Error tells: "Update Requiere que UpdateCommand sea válido cuando se pasa la coleccion DataRow con las Filas Modificadas"
Please Help me.. I need the solution to this problem
I'm working with MS VS 2008 Express in Spanish.

 
Comment #26  (Posted by an unknown user on 03/19/2009)
Rating
This was a great explanation of what has traditionally been a complex idea. It was straight forward without any extra complications.
 
Comment #27  (Posted by cheap oem software on 02/10/2012)
Rating
Z1ef81 It's pleasant sitting at work to distract from it?to relax and read the information written here:DD
 
Comment #28  (Posted by oem software on 02/10/2012)
Rating
JOKqeD Hello! Read the pages not for the first day. Yes, the connection speed is not good. How can I subscribe? I would like to read you in the future!....
 
Sponsored Links