C# Database Connection Tutorial: Connecting to SQL Server and Performing CRUD Operations
Working with a database is a core skill for any C# developer. This guide shows you how to connect to Microsoft SQL Server, execute queries, and bind data to Windows Forms controls.
Fundamentals of Database Connectivity
Whether you’re using Oracle, MySQL, MongoDB, or Microsoft SQL Server, the process of connecting, querying, inserting, updating, and deleting data remains consistent. In this tutorial we’ll focus on SQL Server, using the free SQL Server Express edition.
- Connection string – contains server name, database name, and credentials.
- Credentials – username and password with the necessary privileges.
- Optional parameters – e.g., connection timeout, encryption.
SQL Commands in C#
The SqlCommand class sends SQL statements to the database. Use ExecuteReader for SELECT queries and ExecuteNonQuery for INSERT, UPDATE, and DELETE.
Connecting C# to SQL Server
Below is a minimal Windows Forms example that establishes a connection to a database named Demodb using the credentials sa / demo123. The button click event opens the connection, displays a message, and closes it.
Step 1: Create a Windows Forms project in Visual Studio.
Step 2: Add a Button named btnConnect with the text "Connect".
Step 3: Add the following event handler:
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace DemoApplication1
{
public partial class Form1 : Form
{
public Form1() => InitializeComponent();
private void btnConnect_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=WIN-50GP30FGO75;Initial Catalog=Demodb;User ID=sa;Password=demo123";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
MessageBox.Show("Connection Opened!");
conn.Close();
}
}
}
}
Run the application, click the button, and you’ll see a confirmation message.
Reading Data with SqlDataReader
Assume a table demotb exists with columns TutorialID and TutorialName:
| TutorialID | TutorialName |
|---|---|
| 1 | C# |
| 2 | ASP.NET |
Use the following code to fetch and display the rows:
string sql = "SELECT TutorialID, TutorialName FROM demotb";
using (SqlCommand cmd = new SqlCommand(sql, conn))
using (SqlDataReader reader = cmd.ExecuteReader())
{
string output = "";
while (reader.Read())
{
output += $"ID: {reader["TutorialID"]}, Name: {reader["TutorialName"]}\n";
}
MessageBox.Show(output);
}
Inserting a Record
To add a new tutorial (ID 3, Name VB.NET) execute:
string insertSql = "INSERT INTO demotb (TutorialID, TutorialName) VALUES (3, 'VB.NET')";
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
cmd.ExecuteNonQuery();
}
Updating a Record
Update the tutorial with ID 3 to "VB.NET Complete":
string updateSql = "UPDATE demotb SET TutorialName = 'VB.NET Complete' WHERE TutorialID = 3";
using (SqlCommand cmd = new SqlCommand(updateSql, conn))
{
cmd.ExecuteNonQuery();
}
Deleting a Record
Remove the record with ID 3:
string deleteSql = "DELETE FROM demotb WHERE TutorialID = 3";
using (SqlCommand cmd = new SqlCommand(deleteSql, conn))
{
cmd.ExecuteNonQuery();
}
Binding Controls to Data
Windows Forms offers data binding, eliminating the need for manual UI updates. Drag two TextBox controls onto the form, name them txtID and txtName, and add a BindingNavigator.
Use the Data Source wizard to create a project data source for demotb. Then:
- Select
txtID, go to the Properties window, click DataBindings → Text, and bind todemotbBindingSource – TutorialID. - Repeat for
txtNamewithTutorialName. - Set the
BindingNavigator’sBindingSourceproperty todemotbBindingSource.
Run the form; the text boxes display the first record, and the navigator moves through the rows automatically.
Displaying Data with a DataGridView
Drag a DataGridView onto the form. In its properties, set the DataSource to demotbBindingSource. The grid will populate with all rows from the table.
Summary
- Connect to SQL Server using
SqlConnectionand a proper connection string. - Execute CRUD operations with
SqlCommandandExecuteNonQuery. - Read data with
SqlDataReaderand process rows in awhileloop. - Bind UI controls to a
BindingSourcefor automatic data display and navigation. - Use
DataGridViewto present tabular data instantly.
C Language
- C Strings Made Easy: Declaration, Input, Output, and Library Functions
- Using realloc() in C: Syntax, Best Practices & Example
- Mastering C’s free() Function: Practical Guide & Example
- Mastering Java's split() Method: A Practical Guide with Code Examples
- Reading Files in Java with BufferedReader – A Practical Guide with Examples
- Server Automation: From Desktop Macros to FANG Platforms
- Optimizing Solar Panel and Battery Wiring: Series-Parallel Configurations Explained
- Build a Raspberry Pi NAS Server: Step‑by‑Step Guide to Secure, Wireless File Sharing
- TSOP‑1738 Infrared Receiver: Step‑by‑Step Circuit Connection Guide
- Connect Your Haas CNC to a PC or Laptop: Step‑by‑Step Guide