In this blog you will find ASP.NET 3.5 articles and some code samples. These code samples are created by me and should be working. Thanks for visiting my blog! Happy Dot Netting

Thursday, July 3, 2008

How to execute SQL Query from ASP.NET page

Following example would show how to execute SQL Query from ASP.NET. You may create a function using code below and it anywhere in program.

Please let me know your comments on this. Thanks

Here is the example:  

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Configuration

 -- Get connection string from web.config file. Please see my next post to see how to get connection string from web.config.

 Dim connectionString As String = GetConnectionString1()

 

        Dim queryString As String

         -- Set query here

        queryString = "Select * from application_users"

         -- Declare connection       

        Using connection As New SqlConnection(connectionString)

            Dim command As SqlCommand = connection.CreateCommand()

            command.CommandText = queryString

            Try

                connection.Open()

                 -- Declare data reader to read the result set    

                Dim dataReader As SqlDataReader = command.ExecuteReader()

                Do While dataReader.Read()

                    msgbox dataReader(0)

                    --msgbox dataReader(1)

                Loop

                dataReader.Close()

 

            Catch ex As Exception

                Console.WriteLine(ex.Message)

            End Try

        End Using

No comments: