Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

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.

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:

TutorialIDTutorialName
1C#
2ASP.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:

  1. Select txtID, go to the Properties window, click DataBindings → Text, and bind to demotbBindingSource – TutorialID.
  2. Repeat for txtName with TutorialName.
  3. Set the BindingNavigator’s BindingSource property to demotbBindingSource.

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

C Language

  1. C Strings Made Easy: Declaration, Input, Output, and Library Functions
  2. Using realloc() in C: Syntax, Best Practices & Example
  3. Mastering C’s free() Function: Practical Guide & Example
  4. Mastering Java's split() Method: A Practical Guide with Code Examples
  5. Reading Files in Java with BufferedReader – A Practical Guide with Examples
  6. Server Automation: From Desktop Macros to FANG Platforms
  7. Optimizing Solar Panel and Battery Wiring: Series-Parallel Configurations Explained
  8. Build a Raspberry Pi NAS Server: Step‑by‑Step Guide to Secure, Wireless File Sharing
  9. TSOP‑1738 Infrared Receiver: Step‑by‑Step Circuit Connection Guide
  10. Connect Your Haas CNC to a PC or Laptop: Step‑by‑Step Guide