• 0

[VB] How to run an SQL query on a database?


Question

Hey guys,

Hopefully this is a simple question, I have a Visual Studio 2008 project that?s connected to an SQL server database, Visual Studio can see the tables and data in the database.

I?ve managed to create a query, my question is how do I get a command button to run that query and display the results?

dgrlwz3ojw37b5e78r9y.jpg

Any advice will be appreciated,

Thanks for read:)g :)

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

here we go, i am at work now...

you just need to add a label and button to your form... :)

Imports System.Data
Imports System.Data.SqlClient

Public Class Form1

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		'sql connection
		Dim con As SqlConnection = New SqlConnection("Server=localhost;Initial Catalog=AdventureWorks;Integrated Security=SSPI")

		'your query
		Dim qry As String = "select count(*) from AdventureWorks.Person.Contact"

		'complete command
		Dim cmd As New SqlCommand(qry, con)

		Try
			con.Open()

			Dim dr As SqlDataReader = cmd.ExecuteReader()

			'should only be one value
			While (dr.Read())
				Label1.Text = dr.GetValue(0)
			End While

		Catch ex As Exception

			'show the error
			MessageBox.Show(ex.Message.ToString())

		Finally
			'always close
			con.Close()

		End Try

	End Sub
End Class

Link to comment
Share on other sites

  • 0

Cheers, that really helped me out.

I?ve managed to add a various of SQL quires to my program that work perfectly.

Thanks a lot, much appreciate(Y)Y:):)

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.