Thursday 26 July 2012

Beginning .Net : Insert data into SQL Server Database with C# Examples and VB.Net Examples

You can insert data or records in to SQL Server Database tables using SqlCommand Class.
You can use "ExecuteNonQuery" method of SqlCommand Class.
This article is very useful for .Net Beginners.

Here is example for this.
In this example we insert record in "product_master" table. In this table we have two columns. First product_id it's data type is bigint and this is an Identity column, and Second is product_name it's datatype is nvarchar(500).
"product_id" is an identity column so we did not provide this column in Insert query, this column automatically generate new identical number and stored. so we only insert product_name data in INSERT query.


C# Examples :
        SqlConnection objConn = new SqlConnection();
        objConn.ConnectionString = @"Data Source=.\SQLEXPRESS;" +
                                   "Initial Catalog=TempDatabase;" +
                                   "User ID=sa;Password=sa;";  

        SqlCommand objcmd = new SqlCommand();
        objcmd.CommandText = "Insert INTO product_master(product_name) values(@product_name)";
        objcmd.Parameters.AddWithValue("@product_name", "Cabinet");
        objcmd.CommandType = CommandType.Text;
        objcmd.Connection = objConn;
        objcmd.Connection.Open();

        objcmd.ExecuteNonQuery();
        objcmd.Connection.Close();

        objcmd.Dispose();
        objConn.Dispose();

VB.net Examples :
        Dim objConn As New SqlConnection()
        objConn.ConnectionString = "Data Source=.\SQLEXPRESS;" & _
                                   "Initial Catalog=TempDatabase;" & _
                                   "User ID=sa;Password=sa;"

        Dim objcmd As New SqlCommand()
        objcmd.CommandText = "Insert INTO product_master(product_name) values(@product_name)"
        objcmd.Parameters.AddWithValue("@product_name", "Cabinet")
        objcmd.CommandType = CommandType.Text
        objcmd.Connection = objConn

        objcmd.Connection.Open()

        objcmd.ExecuteNonQuery()
        objcmd.Connection.Close()

        objcmd.Dispose()
        objConn.Dispose()

Learn other ADO.Net Examples over here. Click Here...

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.


3 comments:

  1. For beginners and experts must using "Stored Procedures".SP provides safety, fast and easy managing code. I think Beginners must start with stored procedures too. Using query based Insert or update not using in real work life. At the other hand this is a useful article. You can use that for SP too...

    ReplyDelete
    Replies
    1. Yes , you are right.
      I also wrote post related to call "Stored Procedures" from .Net.
      But, Beginners also know this way to insert records.

      Delete