Lesson 34: Database Intro in VB2022
Learn database fundamentals and how to manage data with VB2022 applications
Key Takeaway
VB2022 uses ADO.NET for database operations, providing powerful tools for connecting to and managing databases efficiently.
Welcome to Lesson 34 of our Visual Basic 2022 Tutorial! Building on previous lessons, we'll explore how to work with databases in your applications. Database programming is essential for creating applications that store, retrieve, and manipulate data.
34.1 Database Fundamentals
Database management systems (DBMS) are essential for modern applications to manage data efficiently. VB2022 uses ADO.NET for database operations.
DBMS
Software systems for creating, managing and interacting with databases
ADO.NET
Microsoft's data access technology for .NET applications
SQL Server
Microsoft's relational database management system
Common Database Systems
Microsoft SQL Server
Enterprise-grade relational database management system
Oracle Database
Multi-model database management system
Microsoft Access
Desktop database management system
MySQL
Popular open-source relational database
34.2 ADO.NET Architecture
ADO.NET provides a rich set of components for creating distributed, data-sharing applications.
Core ADO.NET Objects
SqlConnection
Establishes a connection to a SQL Server data source
DataTable
Stores data for navigation and manipulation
DataAdapter
Bridges data sources and DataTables
Pro Tip: Namespaces
For database operations, import System.Data and System.Data.SqlClient namespaces.
Example 34.1: Database Connection
This example shows how to establish a connection to SQL Server:
Imports System.Data.SqlClient Public Class DatabaseForm Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Define connection string Dim connString As String = "Server=localhost\SQLEXPRESS;Database=ContactsDB;Integrated Security=True;" ' Create SqlConnection object Using conn As New SqlConnection(connString) Try ' Open the connection conn.Open() ' Check connection state If conn.State = ConnectionState.Open Then MessageBox.Show("Database connection successful!", "Connection Status", MessageBoxButtons.OK, MessageBoxIcon.Information) End If Catch ex As SqlException MessageBox.Show("Error connecting to database: " & ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Using End Sub End Class
34.3 Retrieving Data
This example demonstrates how to retrieve data from a database and display it in a DataGridView:
Imports System.Data Imports System.Data.SqlClient Public Class DataForm Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Connection string Dim connString As String = "Server=localhost\SQLEXPRESS;Database=ContactsDB;Integrated Security=True;" ' SQL query Dim query As String = "SELECT ContactID, FirstName, LastName, Email FROM Contacts" ' Create objects Using conn As New SqlConnection(connString) Try conn.Open() ' Create DataAdapter Dim adapter As New SqlDataAdapter(query, conn) ' Create DataTable Dim dt As New DataTable() ' Fill DataTable with data adapter.Fill(dt) ' Bind to DataGridView DataGridView1.DataSource = dt Catch ex As SqlException MessageBox.Show("Database error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Using End Sub End Class
Sample Contacts Table
Contacts
34.4 Inserting Records
This example shows how to insert a new record into a database:
Imports System.Data.SqlClient Public Class InsertForm Private Sub BtnInsert_Click(sender As Object, e As EventArgs) Handles BtnInsert.Click Dim connString As String = "Server=localhost\SQLEXPRESS;Database=ContactsDB;Integrated Security=True;" Dim query As String = "INSERT INTO Contacts (FirstName, LastName, Email) VALUES (@FirstName, @LastName, @Email)" Using conn As New SqlConnection(connString) Using cmd As New SqlCommand(query, conn) ' Add parameters to prevent SQL injection cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text) cmd.Parameters.AddWithValue("@LastName", txtLastName.Text) cmd.Parameters.AddWithValue("@Email", txtEmail.Text) Try conn.Open() Dim rowsAffected = cmd.ExecuteNonQuery() If rowsAffected > 0 Then MessageBox.Show("Record inserted successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information) Else MessageBox.Show("No records were inserted.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information) End If Catch ex As SqlException MessageBox.Show("Error inserting record: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Using End Using End Sub End Class
Database Concepts Summary
Master these essential concepts for database programming in VB2022:
Concept | Description | Key Object |
---|---|---|
Database Connection | Establishing communication with the database | SqlConnection |
Data Retrieval | Fetching data from the database | SqlDataAdapter, DataTable |
Data Manipulation | Inserting, updating, deleting records | SqlCommand |
Data Binding | Connecting data to UI controls | DataGridView, BindingSource |
Security Best Practices
Always use parameterized queries to prevent SQL injection attacks. Never concatenate user input directly into SQL statements.
Connection Management
Use the Using statement to ensure database connections are properly closed and disposed, even if exceptions occur.
Error Handling
Always handle SqlException to provide meaningful error messages and maintain application stability.
Practical Exercises
Apply your database knowledge with these hands-on exercises:
Exercise 1: Database Connection Tester
Create an application that tests database connections with different connection strings.
Exercise 2: Simple Contact Manager
Build an application to view, add, and delete contacts from a database table.
Exercise 3: Data Filtering
Implement search functionality to filter records based on user input.
Exercise 4: Data Validation
Add validation to ensure data integrity before inserting records.
Exercise 5: Error Handling System
Create a robust error handling mechanism for database operations.
Challenge Exercise: Inventory Management
Develop a complete inventory management system with products, categories, and stock tracking.
Next Lesson
Learn how to establish database connections in Lesson 35: Connecting to Databases.
Related Resources

Visual Basic 2022 Made Easy
The ultimate beginner-friendly guide for mastering Windows-based application development using Visual Basic in Visual Studio 2022. Whether you're a student, teacher, hobbyist, or self-learner, this book offers a clear, step-by-step approach to help you get started with ease.
What You'll Learn:
- Control structures and procedures
- Decision-making techniques
- Efficient code organization
- Practical application development
- Best practices in VB2022

Mastering Excel VBA 365
Your ultimate step-by-step guide to automating tasks, building macros, and creating powerful applications within Microsoft Excel 365. Whether you're a student, business professional, or aspiring programmer, this comprehensive handbook will help you unlock the full potential of Excel's VBA.
What You'll Learn:
- Control structures in VBA
- Decision-making techniques
- Data processing and analysis
- Report generation
- Automated workflows