Accessing the Database

The Database Access button first adds a new record to the Database1.mdf database and then retrieves and displays all of the records in the database:

'===================================================
    ' Database Access
    '===================================================
    Private Sub btnDataAccess_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles btnDataAccess.Click

        '---Insert a record into the table---
        Dim conn As New SqlConnection _
        ("Data Source=.\SQLEXPRESS;AttachDbFilename="&_
         "|DataDirectory|\Database1.mdf;Integrated "&_
         "Security=True;User Instance=True")
        Dim sql As String = _
           "INSERT INTO Books (ISBN, Title) VALUES "&_
           "('1-23456-123-x','ABC Guide to ClickOnce')"
        Dim comm As New SqlCommand(sql, conn)
        conn.Open()
        Try
            Dim rowsAdded As Int16 = comm.ExecuteNonQuery()
            MsgBox("Rows added: "&rowsAdded)
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

        '---Read the just inserted data---
        sql = "SELECT * FROM Books"
        Dim reader As SqlDataReader
        comm.CommandText = sql
        reader = comm.ExecuteReader
        While reader.Read
            MsgBox("ISBN: "&reader("ISBN"))
            MsgBox("Title: "&reader("Title"))
        End While
        conn.Close()
    End Sub

Get Use ClickOnce to Deploy Windows Applications now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.