Inserting Data to a Table using ADO.NET in ASP.NET

I will share how to insert a row to a table using SQL Query in Microsoft SQL Server using ADO.NET and ASP.NET. In the previous course we learn about the basic of ADO.NET. We learn about how to query a data from a table in a database. The step can be summarized :

  1. Open a connection to database
  2. Specify the SQL Query to perform the operation
  3. Execute the command
To insert a row we need to change the SQL Query. The general expression of SQL Query to insert a row is :

INSERT INTO table_name(fld1,fld2,...) VALUES ('value1', 'value2','value3',...)


And to perform this query, we need to use the method of ExecuteScalar(). The namespaces that need to be added to do this task are :

using System.Data.Sql;
using System.Data.SqlClient;

To summarize it, the code should be like this.

string connectionString = "Your connection String";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();

SqlCommand command = new SqlCommand();

command.Connection = conn;
command.CommandText = @"INSERT INTO table_name(fld1,fld2)"+
"VALUES ('value1', 'value2')";

command.ExecuteScalar();
conn.Close();

0 comments: