What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 1882 |  Welcome, Guest!   Register  Login
Home > Articles > ADO.NET > How to insert records into the database?

How to insert records into the database?

2 vote(s)
Rating: 4.5 out of 5
Article posted by Sheonarayan on 8/16/2011 | Views: 11761 | Category: ADO.NET | Level: Intermediate | Points: 250 red flag


In this article, we shall learn how to insert records into the SQL Server database.

Introduction

ADO.NET is a mechanism to communicate with the database. It allows us to work in connected (database connection is alive while the operation is performed) as well as disconnected architecture (database connection is closed and operation can be performed on the data).

Get hundreds of ASP.NET Tips and Tricks and ASP.NET Online training here.

In this scenario, we need to connect to the database and insert records into the database, that can be done by following this approach.

Below is my aspx page (aspx.page) to insert records into the database.

ASPX PAGE

<asp:Label ID="lblMessage" runat="server" ForeColor="Green" />

<h5>Create, Read, Update, Delete operation</h5>

<div>

<table>

<tr><td>First name: </td><td><asp:TextBox ID="txtFirstName"

runat="server" /> </td></tr>

<tr><td>Last name: </td><td><asp:TextBox ID="txtLastName"

runat="server" /> </td></tr>

<tr><td>Age: </td><td><asp:TextBox ID="txtAge" runat="server" />

</td></tr>

<tr><td>Active: </td><td>

<asp:DropDownList ID="dropActive" runat="server">

<asp:ListItem Text="Yes" Value="True" />

<asp:ListItem Text="No" Value="False" />

</asp:DropDownList>

</td></tr>

<tr><td>&nbsp;</td><td><asp:Button ID="btnSubmit" runat="server"

Text="Submit" OnClick="SubmitData" /></td></tr>

</table>

</div>

It has basically three text boxes, one dropdown list and a button. On click of the button, SubmitData server side method executes.

CODE BEHIND

 

string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

/// <summary>

/// Submits the data.

/// </summary>

/// <param name="sender">The sender.</param>

/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event

data.</param>

protected void SubmitData(object sender, EventArgs e)

{

int returnValue = 0;

 

// get the connection

using (SqlConnection conn = new SqlConnection(_connStr))

{

// write the sql statement to execute

string sql = "INSERT INTO PersonalDetail (FirstName, LastName, Age, Active)

VALUES " +

"(@FirstName, @LastName, @Age, @Active)";

// instantiate the command object to fire

using (SqlCommand cmd = new SqlCommand(sql, conn))

{

// attach the parameter to pass, if no parameter is in the sql no need to

attach

SqlParameter[] prms = new SqlParameter[4];

prms[0] = new SqlParameter("@FirstName", SqlDbType.VarChar, 50);

prms[0].Value = txtFirstName.Text.Trim();

prms[1] = new SqlParameter("@LastName", SqlDbType.VarChar, 50);

prms[1].Value = txtLastName.Text.Trim();

prms[2] = new SqlParameter("@Age", SqlDbType.Int);

prms[2].Value = int.Parse(txtAge.Text.Trim());

prms[3] = new SqlParameter("@Active", SqlDbType.Bit);

prms[3].Value = bool.Parse(dropActive.SelectedValue);

 

cmd.Parameters.AddRange(prms);

conn.Open();

returnValue = cmd.ExecuteNonQuery();

conn.Close();

}

}

if (!returnValue.Equals(0))

{

lblMessage.Text = " Records inserted successfully !";

}

}

In the above code snippet, on the aspx page we have three TextBoxes, a DropDownList (First name, Last name, Age & Active) and a Submit button. On click of the Submit, we have attached the SubmitData server side method.

In the SubmitData method, we have a SqlConnection object and SqlCommand object in the same way we had for fetching the records from the database. The only change here is the sql command that is going to execute. As our sql command has four parameters, we need to attach four SqlParameters to the command object. To execute the Insert, Update and Delete sql query, we need to fire the ExecuteNonQuery method of the command object (before executing this command, ensure that the database connection is open and after executing close this immediately to avoid any memory leak).

ExecuteNonQuery method returns number of records affected with the Sql statement. So we have checked if it is not equal to 0 and then wrote the success message as displayed in the picture below.

OUTPUT

As written in the last article, we are using the using {} block so we do not need to explicitly dispose the SqlConnection, SqlCommand objects once we are done with them.

NOTE: In the real time project, you should use Stored Procedure rather than using inline sql statements. We shall learn about how to use Stored Procedure in coming up article.

Thanks for reading and keep reading, learning and sharing, after all it increases the knowledge !


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

 Responses
Posted by: A4u_6178 | Posted on: 16 Aug 2011 08:52:01 AM | Points: 25

Hello sir ,
correction needed..
It has basically three radio buttons, one dropdown list and a button. On click of the button, SubmitData server side method executes
Your form doesn't contain any radio button in it.It contains three textboxes.

Posted by: SheoNarayan | Posted on: 16 Aug 2011 09:34:50 AM | Points: 25

Dear A4u_6178,

Thanks for pointing out the typo. I have corrected.

Regards


Posted by: Vishvvas | Posted on: 17 Aug 2011 04:33:23 PM | Points: 25

Just curious about the note where it is mentioned to use stored procedure inplace of inlinesql. Any specific reasons?

>> Write Response - Respond to this post and get points
Related Posts

We will see overview of Changing database records.

In this article, we will earn how to get the value from output parameter in C# which is returned by stored procedure; also we will see how to get the newly inserted record’s Incremented PK value using output parameter. In this article we used @@Identity sql server variable which tracks the incremented value on the table.

DataTableReader is a very useful ADO.NET class that can be used to retrieve / pass the data between layers in readonly and forward only format. In this article, I shall discuss about the DataTableReader class. Its very useful but perhaps rarely used in everyday programming even if it is best suitable in passing data between layers in place of DataTable.

In this article, we shall learn how to retrieve records from SqlDataReader.

This post will show you how to perform crud operations on master details with ease. It also shows you how you can embed your business validation rules within the Entity Framework classes. Also give insight of WPF DataGrid

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/26/2013 4:46:28 AM