Learn how to connect to a database, run queries, and perform CRUD operations with VB.NET. You’ll work with **SQL Server** (or SQLite) to manipulate data. This tutorial includes safe querying with parameterized queries to prevent SQL injection attacks!
📚 Example Code: Connecting to a SQL Server Database
Console output will appear here...
🔑 Pro Tip: Always close your database connections using connection.Close() in the Finally block to ensure it's closed even if an error occurs.
🔧 How This Code Works
SqlConnection creates a connection to the database
Open() establishes the connection to SQL Server
Catch handles exceptions, like connection failures
Finally ensures the connection is closed after usage
🧠 CRUD Operations
Create (Insert) — Insert data into the database
Read (Select) — Retrieve data from the database
Update — Modify existing data
Delete — Remove data from the database
📂 Example Code: Performing CRUD Operations
CRUD output will appear here...
💡 ExecuteNonQuery() is used for commands that don't return data (like INSERT, UPDATE, DELETE). For SELECT queries, use ExecuteReader().
🔐 Prevent SQL Injection
Use Parameters.AddWithValue() to safely insert user input into SQL queries. This avoids SQL injection, where malicious users inject harmful SQL commands.
📂 Example Code: Safe SELECT Query with Parameters
Select output will appear here...
⚠️ Always use parameterized queries to prevent **SQL Injection** attacks — never concatenate user input directly into queries.
🧰 Handling Database Errors
Connection Issues — Make sure the connection string is correct and the database is running.
SQL Errors — Handle SQL-related errors like syntax issues with Catch ex As SqlException.
Timeouts — Handle connection timeouts with SqlCommand.CommandTimeout.