How to Insert values into MS SQL Server using C#

In this tutorial, we will learn how to insert values into MS SQL Server using C#. For this specific tutorial, we’ll use Windows forms application which is a very popular platform for designing and development of desktop applications C#. You can also use this technique in Web Forms applications and WPF if you want.

Tools Required:
  1. Visual Studio 2010 or later version.
  2. MS SQL Server 2008 or later version.
  3. SLR Db Connector Library. Download it from this Link for Free.

SLR Db Connector library is a free and opensource ADO .NET based library designed by C# Ui Academy to perform basic database operations for beginners with C# and MS SQL Server. It is a best tool to communicate with database for beginners.

In order to use SLRDbConnector, we must have the MS SQL Server installed on our machine. So, I assume you already have installed the MS SQL Server and its Management studio in your PC.

Steps to Follow:
  1. Open the MS SQL Management studio and go to your database and create a new table.
  2. Lets say we have a table called Students with columns of Name, Father Name and Registration Number respectively.
  3. Go to your app.config file in visual studio project and declare a connection string between <configuration></configuration> tags like:
        <add name="ConnString"
            connectionString="Data Source=DESKTOP-CFLOBRQ\SQLEXPRESS;Initial Catalog=StudentDb; Integrated Security=True; providerName="System.Data.SqlClient" />

Now add the SLRDbConnector into your references and go to your code. Import the SLR Db Connector namespace on the top of your class.

To perform any database operation, declare an object of DbConnector Class on right above the constructor like:

DbConnector db = new DbConnector();

Performing CRUD (Create Read Update Delete) using SLR Db Connector is really easy. To insert values into SQL, Just pass your query as a parameter to perform your desired operation. You can insert values into the table using the below code:

db.performCRUD("insert into Students(name,father_name,reg_no) values('"+txtName.Text+"','"+txtFatherName.Text+"','"+txtRegNumber.Text+"')");
//This will insert values into SQL 

In the above code, txtName is the name of your name textbox, txtFatherName is name of father name textbox and txtRegNumber is name of the textbox for registration number respectively.

The best thing about the methods of SLR Db connector is, It will always return a string response when we use any method. The returned string will show the response of the Database like,

string message = db.performCRUD("insert into Students(name,father_name,reg_no) values('"+txtName.Text+"','"+txtFatherName.Text+"','"+txtRegNumber.Text+"')");;
//This will return the message of success, failed of exception with reason.

I hope you enjoyed this tutorial, Please subscribe our official YouTube Channel C# Ui Academy.