.Net Howto - Connecting to a Database
The following example illustrates how to connect to a database using a connectionstring. We’re also using a datareader to access multiple rows, and a scalar to access a single value.
Dim objConn As New SqlConnection Dim objComm As New SqlCommand Dim objReader As SqlDataReader Dim strText As String
Try objConn.ConnectionString = "server=(local);database=northwind;integrated security=SSPI" objConn.Open() MessageBox.Show("Connection Success!") objComm.Connection = objConn objComm.CommandType = CommandType.Text objComm.CommandText = "SELECT @@VERSION" MessageBox.Show(objComm.ExecuteScalar()) objComm.CommandText = "SELECT companyname FROM customers ORDER BY companyname" objReader = objComm.ExecuteReader 'read must be done first to prime the data reader. 'if trying to access item(0) prior to doing a read an exceptionwill occur! While objReader.Read strText += objReader.Item(0) + NewLine End While MessageBox.Show(strText) Catch objError As Exception MessageBox.Show(objError.Message) End Try
As you can see this is a fairly simple example using the Northwind database. More info will be soon to come on creating your own connectionstrings, etc.