Connect To Database uing ASP.Net

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Connect To Database uing ASP.Net

Post by Neo » Sun Mar 21, 2010 6:47 pm

In this asp.net example you will see how to connect to a database and extract some data from it, then finally bind it to a datareader.

This is the real essence of server side language such as ASP.Net, connecting to database, saving from database etc. that's how lot of websites are built, and work with data.

From this code, you can extract the parts that are required for your application.

Code: Select all

import System.Data
import System.Data.SqlClient

    Function ConnectToDB(byval select_string, byval username as string, byval password as string, byval server as string, byval database as string)
    
        'this is declaring the sqlconnection, the sql command statement and the datareader
        
        Dim connection_ As SqlConnection
        Dim sqlcommand_ As SqlCommand
        Dim SqlDataReader_ As SqlDataReader 'Here we make the connection, put in the server adresse, login username, password and database

        connection_ = New SqlConnection( "server=YOURSERVER; uid=username; pwd=password; database=YOURDATABASE")

        'Opening the connection
        connection_.Open 
        
        cmdLath = New SqlCommand (select_string, connection_)
        
        SqlDataReader_ = cmdLath.ExecuteReader
        datareader.DataSource = rdrLath
        datareader.DataBind
        
        'Always remember to close your connections, even though many servers auto close or has a timeout closing 
        
        SqlDataReader_.Close
        sqlcommand_.Dispose
        connection_.Close
    
    End function
Post Reply

Return to “ASP & ASP.Net”