How To Use A Database In Your Program

Discussion in 'Databases' started by largn81, Jan 26, 2008.

  1. #1
    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:

    Code: ( vbnet )
    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.

    Code: ( vbnet )
    dim dbCon As SqlConnection
    dbCon = New SqlConnection(connectionString)


    Code: ( cpp )
    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.


    Code: ( vbnet )
    Dim sqlCom As New SqlCommand


    Code: ( cpp )
    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:


    Code: ( vbnet )
    sqlCom.Connection = dbCon
    sqlcom.CommandType = CommandType.Text
    sqlCom.CommandText = "INSERT INTO CONTACT(cID, cAddress, cPhoneNumber)" _
    " VALUES(@cID,@cAddress,@cPhoneNumber)"
    sqlCom.Parameters.Add("@cID", SqlDbType.Int).Value = 1234567
    sqlCom.Parmaeters.Add("@cAddress", SqlDbType.VarChar).Value = "123 Hypoth. Street..."
    sqlCom.Parameters.Add("@cPhoneNumber",SqlDbType.VarChar).Value="1-800-999-99999"


    Code: ( cpp )
    sqlCom.Connection = dbCon;
    sqlcom.CommandType = CommandType.Text;
    sqlCom.CommandText = "INSERT INTO CONTACT(cID, cAddress, cPhoneNumber)" +
    " VALUES(@cID,@cAddress,@cPhoneNumber)";
    sqlCom.Parameters.Add("@cID", SqlDbType.Int).Value = 1234567;
    sqlCom.Parmaeters.Add("@cAddress", SqlDbType.VarChar).Value = "123 Hypoth. Street...";
    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


    Code: ( vbnet )
    Try
    dbCon.Open()
    sqlcom.ExecuteNonQuery
    dbCon.Close()
    Catch ex As Exception

    End Try



    Code: ( cpp )
    try
    {
    dbCon.Open();
    sqlcom.ExecuteNonQuery();
    dbCon.Close();
    }
    catch(Exception ex)
    {

    }


    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.

    Code: ( vbnet )
    Try
    Dim dr As SqlDataReader
    dbCon.Open()
    dr = sqlcom.ExecuteReader

    If dr.HasRows = True Then
    txt_clientID.Text = CType(dr("cID"),Integer).ToString()
    txt_clientAddress.Text = CType( dr("cAddress"),String)
    txt_clientPhoneNumber.Text = CType(dr("cPhoneNumber"),String)
    End If

    dr.Close()
    dbCon.Close()

    Catch ex As Exception

    End Try


    Code: ( cpp )
    try
    {
    SqlDataReader dr;
    dbCon.Open();
    dr = sqlcom.ExecuteReader();

    if(dr.HasRows == True)
    {
    txt_clientID.Text = ((Integer) dr["cID"]).ToString();
    txt_clientAddress.Text = (String) dr["cAddress"];
    txt_clientPhoneNumber.Text = (String) dr["cPhoneNumber"];
    }

    dr.Close();
    dbCon.Close();
    }
    catch(Exception ex)
    {

    }

    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:

    Code: ( vbnet )
    While dr.Read
    txt_clientID.Text = txt_clientID.Text + CType(dr("cID"),Integer).ToString()
    End While



    Code: ( cpp )
    while(dr.Read())
    {
    txt_clientID.Text = txt_clientID.Text + ((Integer)dr["cID"]).ToString();
    }

    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!
    :)
     
    largn81, Jan 26, 2008 IP
  2. AstarothSolutions

    AstarothSolutions Peon

    Messages:
    2,680
    Likes Received:
    77
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Firstly, if your going to be using error catching why not use
    Try
    <open the connection, execute the sqlcommand>
    Catch
    <Handle the error>
    Finally
    <Close the connection here>
    End Try

    This way you ensure the connection is closed and you dont end up with a host of unclosed connections if an error occurs

    Likewise, you really should consider using stored procedures rather than direct queries
     
    AstarothSolutions, Jan 26, 2008 IP