Search code examples
c#sqlasp.netstored-proceduresado.net-entity-data-model

Inserting data in database in Asp.Net . Which way is better?


I am working on a Asp.Net website to insert data in the database. After reading different articles on internet where it is suggested that we should use a parametrized query as it prevents from SQL Injection attacks.

So I am wondering which way is better:

Create a Stored Procedure with parameters in the database and then call it in the button click event to insert the data in the database e.g.

CREATE PROCEDURE AddInfraction
@Description varchar(255), @Penalty money, @Points int
AS
  BEGIN
       INSERT INTO Infractions (Description, Penalty, Points)
       VALUES (@Description, @Penalty, @Points)
  END

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand("AddInfraction"))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("Description", Description.Text);
                command.Parameters.AddWithValue("Penalty", Convert.ToInt16(Penalty.Text));
                command.Parameters.AddWithValue("Points", Convert.ToInt16(Points.Text));
                connection.Open();
                queryResult = command.ExecuteNonQuery();
                if (queryResult == 0)
                {
                    return;
                }
            }
            connection.Close();
        }

Or maybe first by adding the ADO.NET Entity Data Model in the database and then in the button click event creating the object of the data model recently added, and then call the particular stored procedure and inserting the data in the database.

using (ETrafficChallanSystemEntities eTrafficChallanSystemEntities = new ETrafficChallanSystemEntities())
{
  eTrafficChallanSystemEntities.AddInfraction(Description.Text, 
  Convert.ToInt16(Penalty.Text), Convert.ToInt16(Points.Text));
}

Which one would be the best way to insert data in the database.


Solution

  • Both the methods are good to insert data in the database. Using a parameterized query is always a good option. I would suggest using the second method as you have already added the ADO.NET Entity Model in your project.