Fortune
Fortune

Reputation: 1

Insert data into a SQL Server database using ASP.NET is not working

I wrote code to insert data into the database, after I click the insert button, nothing happens and there is no error. Please I need help.

If I click the insert button from the front end, it is supposed to populate the database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace insertAdo
{
    public partial class TableInsert : System.Web.UI.Page
    {
        protected void Button1_Click(object sender, EventArgs e)
        {
            string connectionString;
            SqlConnection cnn;

            connectionString = @"Data Source=DESKTOP-5JPBK1L;Database=StudentDB; Integrated Security=SSPI";

            cnn = new SqlConnection(connectionString);

            cnn.Open();
            {
                SqlCommand command;
                SqlDataAdapter adapter = new SqlDataAdapter();
                String sql = "";

                sql = "INSERT INTO  student_table (Student_id, name, Email, Join_date) VALUES (102, 'Jaja Peter', '[email protected]', '09/30/2021')";

                command = new SqlCommand(sql, cnn);
                adapter.InsertCommand = new SqlCommand(sql, cnn);
                adapter.InsertCommand.ExecuteNonQuery();

                command.Dispose();
            }

            Response.Write("Insert successful");
            cnn.Close();
        }
    }
}

Upvotes: 0

Views: 646

Answers (1)

Anand Sowmithiran
Anand Sowmithiran

Reputation: 2920

First ensure that your front-end UI button's Click event is wired up , like below in your aspx page.

 <asp:Button id="Button1"
           Text="Click here for inserting..."
           OnClick="Button1_Click" 
           runat="server"/>

After that make the modification in your .cs code file as below.

    string connectionString = @"Data Source=DESKTOP-5JPBK1L;Database=StudentDB; Integrated Security=SSPI";

    string sql = "Insert into student_table(Student_id,name,Email,Join_date) values(102,'Jaja Peter','[email protected]','09/30/2021')";

    // create connection and command
    using(SqlConnection cn = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(sql, cn))
    {
        // open connection, execute INSERT, close connection
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }

Use of the using block ensures that your connection and command objects are disposed properly.

For learning, this way of hard coding the values is okay, but in real world scenario, you would need to use parameters, and use model class, not have the connecting string inside your code etc.

Upvotes: 1

Related Questions