Write a VB.NET program to create a table Patient (PID, PName, Contact No, Disease). Insert five records into the table and display an appropriate message in a message box.

Answer:

Sample Patient Table (PatientDB.accdb):

PID (AutoNumber)PNameContactNoDisease
1John Doe123-456-7890Flu
2Jane Smith987-654-3210Cold
3Sam Brown555-555-5555Pneumonia
4Emma White111-222-3333Asthma
5Oliver Green444-555-6666Cancer
Imports System.Data.OleDb

Public Class Form1
    Dim conn As OleDbConnection
    Dim cmd As OleDbCommand
    Dim connString As String

    ' This is the connection string to your Access database
    ' Make sure to replace with the correct path to your .accdb file
    connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Path\To\Your\Database\PatientDB.accdb;Persist Security Info=False;"

    ' The Button click event to insert records and show message box
    Private Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
        Try
            ' Open the connection
            conn = New OleDbConnection(connString)
            conn.Open()

            ' Insert five records into the Patient table
            Dim insertQuery As String = "INSERT INTO Patient (PName, ContactNo, Disease) VALUES " &
                                        "('John Doe', '123-456-7890', 'Flu')," &
                                        "('Jane Smith', '987-654-3210', 'Cold')," &
                                        "('Sam Brown', '555-555-5555', 'Pneumonia')," &
                                        "('Emma White', '111-222-3333', 'Asthma')," &
                                        "('Oliver Green', '444-555-6666', 'Cancer')"

            ' Execute the insert query
            cmd = New OleDbCommand(insertQuery, conn)
            cmd.ExecuteNonQuery()

            ' Display success message
            MessageBox.Show("Records inserted successfully into the Patient table.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)

        Catch ex As Exception
            ' Display error message if something goes wrong
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            ' Ensure the connection is closed
            If conn IsNot Nothing AndAlso conn.State = ConnectionState.Open Then
                conn.Close()
            End If
        End Try
    End Sub
End Class
Scroll to Top