RSS link icon

.

asp.net Simple Connect To Database


I have been wondering what level of programming experience my blog readers have, my guess is some of them have a fair amount of knowledge but not too much, and thats why you are here, to get better.

Now if you are new to asp.net this might go over your head, but try to follow, and if you succeed in following this function you will also be able to use it. 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. its how a lot of websites is build, and work with data.

Text with green color is the explanations you should follow to understand how the function works. But eventually you should be able to copy the function part and put it in your code, then call the function ConnectToDB define the select statement, username, password, server and database.

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

Hope you enjoyed the code, and it was not to confusing.


shane says: 2008-09-29

import is not valid

LIUFA says: 2008-05-09

where does datareader.DataSource = rdrLath datareader.DataBind comes from

murali says: 2007-11-02

welcome to all

murali says: 2007-11-02

murali

padkm says: 2007-11-02

hai