Tuesday, January 24, 2023

How do I Insert data in SQL Server using ASP .Net

To insert data into a SQL Server database using ASP.NET, you can use the ADO.NET library to establish a connection to the database and execute an INSERT statement. Here is an example of how to do this:

1.    Create a new ASP.NET project and add a reference to the System.Data.SqlClient namespace.

2.    Create a new method that will handle the insertion of data.

3.    In this method, create a new SqlConnection object and set the connection string to the appropriate value for your SQL Server database.

4.    Open the connection using the Open() method.

5.    Create a new SqlCommand object and set the CommandText property to the INSERT statement you want to execute.

6.    Add any necessary parameters to the SqlCommand object using the Parameters.Add() method.

7.    Execute the command using the ExecuteNonQuery() method.

8.    Close the connection using the Close() method.

Here is an example of how your code might look:

using (SqlConnection con = new SqlConnection("Data Source=myServer;Initial Catalog=myDB;User ID=myUsername;Password=myPassword"))

{

    con.Open();

    using (SqlCommand cmd = new SqlCommand("INSERT INTO myTable (col1, col2) VALUES (@val1, @val2)", con))

    {

        cmd.Parameters.AddWithValue("@val1", "some value");

        cmd.Parameters.AddWithValue("@val2", 123);

        cmd.ExecuteNonQuery();

    }

    con.Close();

 

 

No comments: