Sign In | Register Now About Bytes | Help | Site Map
Connecting Tech Pros Worldwide

How To Use A Database In Your Program

Written by Frinavale, April 20th, 2007
How To Use A Database In Your Program
Many .NET solutions are database driven and so many of us often wonder how to access the database. To help you understand the answer to this question I've provided the following as a quick example of how to retrieve data from a database.

In order to connect to a database using .NET you will need to import the System.Data.SqlClient package into your program.

The following examples are done using VB.NET but can easily be converted into C#.

Connection String
The first thing you'll need to do (after you've created the database) is connect to it. In order to do this you have to define something called a Connection String.

The Connection String is used as a means to locate the database your program will be using.
A Connection String is typically formatted as follows:
Expand|Select|Wrap|Line Numbers
  1. connectionString="data source=<nameOfDatabaseServer>;initial catalog=<nameOfDatabase>;user id=<databaseUserId>;password=<passwordForDatabaseUser>"

Since Connection Strings contain very sensitive information on how to access the database it is crucial that you protect it (by encryption or other means). If you are implementing a web application, it is a good idea to store this information in the web.config file so that it is easily protected.

SqlConnection
Once you have created a connection string you have to create an SqlConnection object. This object uses the connection string to form a connection to the database for you.
Expand|Select|Wrap|Line Numbers
  1. dim dbCon As SqlConnection
  2. dbCon = New SqlConnection(connectionString)

Expand|Select|Wrap|Line Numbers
  1.      SqlConnetion dbCon= new SqlConnection(connectionString);


SqlCommand
After you have created an instance of an SqlConnection object, you need to create an SqlCommand. This object is used to carry out the sql commands that will be executed by the database.

Expand|Select|Wrap|Line Numbers
  1. Dim sqlCom As New SqlCommand

Expand|Select|Wrap|Line Numbers
  1. SqlCommand sqlCom = new SqlCommand();


Once we have an instance of this object we need to set some of its properties.

First of all you have to specify what type of SqlCommand you are going to be executing. This is where you specify if you are using a store procedure or if you'll be supplying an SQL statement to be carried out. In this example we'll cover how to supply your own SQL statement.

You'll have to set the SqlCommand's "CommandText" property to be the SQL commands that need to be carried out by the function you're creating.

Once you've set the "CommandText" property, you'll have to add the values of any parameters used in the SQL command statement. You do this by setting the SqlCommand's "Parameters" property.

You also have to set the SqlCommand object's "Connection" property to the SqlConnection object you created earlier in order to connect to the database.

For example, if you would like to insert a new contact entry into a table you would set the SqlCommand's "CommandText" to be something like:

Expand|Select|Wrap|Line Numbers
  1. sqlCom.Connection = dbCon
  2. sqlcom.CommandType = CommandType.Text
  3. sqlCom.CommandText = "INSERT INTO CONTACT(cID, cAddress, cPhoneNumber)" _
  4. " VALUES(@cID,@cAddress,@cPhoneNumber)"
  5. sqlCom.Parameters.Add("@cID", SqlDbType.Int).Value = 1234567
  6. sqlCom.Parmaeters.Add("@cAddress", SqlDbType.VarChar).Value = "123 Hypoth. Street..."
  7. sqlCom.Parameters.Add("@cPhoneNumber",SqlDbType.VarChar).Value="1-800-999-99999"

Expand|Select|Wrap|Line Numbers
  1. sqlCom.Connection = dbCon;
  2. sqlcom.CommandType = CommandType.Text;
  3. sqlCom.CommandText = "INSERT INTO CONTACT(cID, cAddress, cPhoneNumber)" +
  4. " VALUES(@cID,@cAddress,@cPhoneNumber)";
  5. sqlCom.Parameters.Add("@cID", SqlDbType.Int).Value = 1234567;
  6. sqlCom.Parmaeters.Add("@cAddress", SqlDbType.VarChar).Value = "123 Hypoth. Street...";
  7. sqlCom.Parameters.Add("@cPhoneNumber",SqlDbType.VarChar).Value="1-800-999-99999";

Executing Your SQL Commands
After you've set up everything you can carry out your SQL commands on the database.
To do this you have to:
  • first open a connection to the the database
  • and then execute the SQL command
  • and finally close the connection

Expand|Select|Wrap|Line Numbers
  1. Try
  2.     dbCon.Open()
  3.     sqlcom.ExecuteNonQuery
  4.     dbCon.Close()
  5. Catch ex As Exception
  6.  
  7. End Try


Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3.     dbCon.Open();
  4.     sqlcom.ExecuteNonQuery();
  5.     dbCon.Close();
  6. }
  7. catch(Exception ex)
  8. {
  9.  
  10. }


In the above code we used the ExecuteNonQuery command because updating the table does not return any results. You can determine if it executed correctly by checking to see if this sqlcom.ExecuteNonQuery = 1.

If you are executing an SQL command that returns a result, such as executing a SELECT statement you will have to store the information somehow.

The following snippet of code shows you how to store the results into an SqlDataReader object.
Expand|Select|Wrap|Line Numbers
  1. Try
  2.     Dim dr As SqlDataReader
  3.     dbCon.Open()
  4.     dr = sqlcom.ExecuteReader
  5.  
  6.     If dr.HasRows = True Then
  7.         txt_clientID.Text = CType(dr("cID"),Integer).ToString()
  8.         txt_clientAddress.Text = CType( dr("cAddress"),String)
  9.         txt_clientPhoneNumber.Text = CType(dr("cPhoneNumber"),String)
  10.     End If
  11.  
  12.     dr.Close()
  13.     dbCon.Close()
  14.  
  15. Catch ex As Exception
  16.  
  17. End Try

Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3.     SqlDataReader dr;
  4.     dbCon.Open();
  5.     dr = sqlcom.ExecuteReader();
  6.  
  7.     if(dr.HasRows == True)
  8.     {
  9.         txt_clientID.Text = ((Integer) dr["cID"]).ToString();
  10.         txt_clientAddress.Text = (String) dr["cAddress"];
  11.         txt_clientPhoneNumber.Text = (String) dr["cPhoneNumber"];
  12.     }
  13.  
  14.     dr.Close();
  15.     dbCon.Close();
  16. }
  17. catch(Exception ex)
  18. {
  19.  
  20. }

Once you are finished with your SqlDataReader object be sure to close it to clean up.

If your Sql command returns more than one row, you will have to loop through the data reader to retrieve all of the information.

For example the following will add all of the "clientID's" to the TextBox txt_clientID:
Expand|Select|Wrap|Line Numbers
  1. While dr.Read
  2.           txt_clientID.Text =  txt_clientID.Text + CType(dr("cID"),Integer).ToString()
  3. End While


Expand|Select|Wrap|Line Numbers
  1. while(dr.Read())
  2. {
  3.           txt_clientID.Text =  txt_clientID.Text + ((Integer)dr["cID"]).ToString();
  4. }

Other Notes
The objects used to connect to a database implement the iDisposable interface. Because of this it is Strongly advisable to define a Dispose() method that will properly handle the disposal of any connections. Be sure to look up how to implement this method to properly clean up your memory. It really helps to manage your resources.

Hope you find this useful!

-Frinny

Last edited by Frinavale : December 29th, 2007 at 05:06 PM. Reason: added C# code snippets to example
14 Comments Posted ( Post your comment )
dwadish / May 22nd, 2007 02:32 PM
Friend
I know how to connect to a database and it's connection string also

but this error not from the connection string.

give a good solution.

Thanx for the reply
KUB365 / November 21st, 2007 01:21 PM
This is a good article. Very detailed.
sevilay / December 3rd, 2007 07:28 AM
Quote:
Friend
I know how to connect to a database and it's connection string also

but this error not from the connection string.

give a good solution.

Thanx for the reply


could you tell me for one example . because it is first time for me to write
i know in VB.net but i don't know in C# by using Console
sevilay / December 3rd, 2007 07:32 AM
coul you tell me it is first time for me i know how i connect in VB.net i have so many how work next week .
just for one example in C# by using Console
Frinavale / December 3rd, 2007 01:08 PM
The example is almost exactly the same for C#.
You just have to change the syntax from VB.NET to C#.

For example, you'd declare your variables like this in VB:
Expand|Select|Wrap|Line Numbers
  1.       Dim dbCon As SqlConnection

And in C# you would declare your variables like this:
Expand|Select|Wrap|Line Numbers
  1.       SqlConnection dbCon;


Since both C# and VB.NET use the same Framework, you will have access to the same data types in both languages.

Try to follow the example and when you run into problems post your question about the specific problem in the .Net forum.

-Frinny
ssknov / January 2nd, 2008 07:29 AM
hi frinav
fine article.
it ll be good if u can add examples for Executescalar, Datatable.

thnk u
kssk
Frinavale / January 2nd, 2008 01:07 PM
Quote:
hi frinav
fine article.
it ll be good if u can add examples for Executescalar, Datatable.

thnk u
kssk


I've never heard of ExecuteScalar, DataTable...
Do you mean a GridView (or DataGrid)??

-Frinny
jallred / March 3rd, 2008 06:55 PM
If you're using .NET 3.5, consider using LINQ (Language Integrated Query).

Assume that you have a customer database. The following query would select the customers in Oregon:

Customer[] Customers = GetCustomers();
var query =
from c in Customers
where c.State == "Oregon"
select c;

Quick and easy!
John
Frinavale / March 4th, 2008 01:05 PM
Quote:
If you're using .NET 3.5, consider using LINQ (Language Integrated Query).

Assume that you have a customer database. The following query would select the customers in Oregon:

Customer[] Customers = GetCustomers();
var query =
from c in Customers
where c.State == "Oregon"
select c;

Quick and easy!
John

Thanks for the info John :)
I'm going to have to look up LINQ!

-Frinny
dwadish / March 7th, 2008 08:00 AM
I know the connectivity with framework 2.0 and other previous versions but 3.5
LINQ
Wow really fantastic
Last edited by dwadish : March 7th, 2008 at 08:02 AM. Reason: missing words
Reply
reese / March 16th, 2008 10:45 AM
How About If Im Going To Use A Database To Connect In A Program Through Php???
How Should It Be Done???
Frinavale / March 17th, 2008 01:07 PM
Quote:
How About If Im Going To Use A Database To Connect In A Program Through Php???
How Should It Be Done???


That is a good question to ask the PHP experts. This article was intended for a .NET audience. Check out the PHP how-to articles, specifically the one about Creating a Data Abstraction Layer in PHP, and also the one on Uploading files into a MySql Database using PHP.

-Frinny
meanmachine / June 20th, 2008 05:19 AM
hey Frinny,

the article you posted about limking vb.net with sql database was informative but i'm a newbie and i need some further assistance to be able to make a project i have been assigned. if you have some other articles or a code bank or something of that fashion kindly advise....

regards,

gaurav
Frinavale / June 20th, 2008 07:47 PM
Quote:
hey Frinny,

the article you posted about limking vb.net with sql database was informative but i'm a newbie and i need some further assistance to be able to make a project i have been assigned. if you have some other articles or a code bank or something of that fashion kindly advise....

regards,

gaurav


At this time I don't have any other materials on using databases.
You should post your specific questions in the .Net Forum. You should get the help you need there.

-Frinny

Stats:
Comments: 14