How to insert data in a Database in C#, SQL Server and ASP.NET

How to insert data in a Database in C#, SQL Server and ASP.NET

With cSharp(commonly known as C#) we can easily do ADO.NET programming to access a database, insert data into database tables, retrieve data from database tables and update data in the database tables. This is a tutorial suited for anyone who would like to get started working with databases in C# by using ADO.NET.

Entity Framework Core – Do you know that with Entity Framework Core, you can also do inserting of data, and all other database operations just like ADO.NET.

In this C# Database Tutorial I will teach you how to insert data into a database.

c# Insert Into SQL Application

My application is a simple one which inserts email address, to the database table, on a button click. The web page has just 2 controls one textbox for email and other a submit button. The application uses Asp.Net with C# as the programming language. The database which I am using is SQL Server.

The HTML Code

<p>Insert Into Database</p>
<p id="messageParagraph" runat="server"></p>
<div>
    <asp:TextBox ID="emailTextBox" runat="server" placeholder="Enter an email address"></asp:TextBox>   
</div>
<div>
    <asp:Button ID="submitButton" runat="Server" Text="Submit" OnClick="submitButton_Click" />
</div>

Connection String in Web.Config

Add a database connection string in the web.config file. It looks similar to –

<connectionStrings>
    <add name="saCS" connectionString="Data Source=yourdatabaseserver;Initial Catalog=yourdatabasename;Persist Security Info=True;User ID=yourdatabaseuserid;Password=yourdatabasepassword" providerName="System.Data.SqlClient"/>
</connectionStrings>

SQL Server Table and Stored Procedure

The SQL table contains only an email field of type Varchar(100). I am using stored procedure for inserting the emails in this table. The stored procedure is given below:

CREATE PROCEDURE [dbo].[sp_InsertEmail]
    @Email    VARCHAR(100),
AS
BEGIN
    INSERT INTO Email(Email) VALUES (@Email)
END

C# Button click Function

protected void submitButton_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString =  ConfigurationManager.ConnectionStrings["saCS"].ConnectionString;

    SqlCommand cmd = new SqlCommand("sp_InsertEmail", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100);
    cmd.Parameters["@Email"].Value = emailTextBox.Text;

    conn.Open();
    int i = cmd.ExecuteNonQuery();
    conn.Close();

    if (i==-1)
    {
        messageParagraph.innerHtml="Your email is saved successfully.";
    }
}

You can use external providers like Google to authenticate your users to your site. Check this Google Contacts API tutorial where I have created a Google APP to authenticate users using Google APIs.

Explanation

In the button click event I am calling the stored procedure called sp_InsertEmail, and giving its parameter called @Email a value of emailTextBox.Text.

I have used ADO.NET< classes to execute the stored procedure. The SqlConnection class sets the connection string while SqlCommand sets the name of the stored procedure and it’s parameters.

In the end the stored procedure is executed using the SqlCommand class inbuilt function called ExecuteNonQuery. It returns value of -1 when the stored procedure is executed successfully, which I have checked with an if statement, and shown the message in the messageParagraph.

Hope you like our C# Database Tutorial and with it you are ready to start your ADO.NET programming in C#.

Related tutorial – Session Authentication is a quick way to create login and logout feature in an ASP.NET website. Using this technique you can prevent access to secured pages of your website to non-logged in users.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.