Posted by: Sourav | June 1, 2015

Run SQl Query on SQL Server Using VB.Net


 

Querying sql server from vb.net

 

Go to sql server management studio right click on test table

 

Script table as-insert to-new query editor window

 

Populate the table using the syntax

INSERT INTO [test].[dbo].[test]

           ([ID]

           ,[Name])

     VALUES

           (1

           ,’Avinash’)

GO

 

Insert some more records

Now on the Sqlcon.vb class file add this subroutine

Public Sub runquery(query As String)

       Try

           sqlcon.Open()

           sqlcommand = New SqlCommand(query, sqlcon)

 

           Dim r As SqlDataReader = sqlcommand.ExecuteReader

           While r.Read

               MsgBox(r.GetName(0) & “:” & r(0))

 

           End While

           sqlcon.Close()

 

       Catch ex As Exception

           MsgBox(ex.Message)

       End Try

 

   End Sub

 

Now go to the form load event

Under this line

MsgBox(“connected”)

Call the subroutine runquery

 

sqlcon.runquery(“select Name from test”)

 

 

ctrl+f5

 

Now go to sql server management studio

 

Add another column on the test table

 

Right click on dbo.test –script table as-update to

New query editor window

 

Write

UPDATE [test].[dbo].[test]

   SET Age=10

WHERE Name=’Sourav’

GO

 

Add age for other names already on test table like this

 

Now go to vs express desktop

Go to form load event

Change the line

sqlcon.runquery(“select Name from test”)

 

 

to this

 

Change the line

sqlcon.runquery(“select Age from test”)

 

ctrl+f5

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: