Using Bind parameters sql command techniques insert data into database table — ADO.Net , C Sharp — ASP.Net Example
ASP.Net Example-Using Bind parameters sql command techniques insert data into database table

Thursday, May 19, 2011

Using Bind parameters sql command techniques insert data into database table

This techniques is better than
using sql command techniques insert data into database table 
because SqlDataAdapter is used here but not optimize solution. 
Bind Parameters techniques for Insert data
using System;
using System.Data;
using System.Data.SqlClient;

class bindParametersExample
{
      static void Main() 
{
string ConnectionString ="server=(local)\\SQLEXPRESS;database=DBTEST;
Integrated Security=SSPI";
string Query = @"select * from aspdotnetTable";
string InsertQuery = @"insert into aspdotnetTable(firstname,lastname)
values(@firstname,@lastname)";

         SqlConnection objConnection = new SqlConnection(ConnectionString );

         try{
            SqlDataAdapter objAd = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand(Query, objConnection );

            DataSet objDs = new DataSet();   
            objAd.Fill(objDs , "aspdotnetTable");

            DataTable objDataTable = objDs.Tables["aspdotnetTable"];

            DataRow objRow = objDataTable.NewRow();
            objRow["firstname"] = "Bill";
            objRow["lastname"] = "Gates";
            objDataTable.Rows.Add(objRow);

            foreach (DataRow row in objDataTable.Rows){
               Console.WriteLine(
                  "{0} {1}",
                  row["firstname"].ToString().PadRight(15),
                  row["lastname"].ToString().PadLeft(25));
            }

            // Insert data in to aspdotnetTable
       SqlCommand objCmd = new SqlCommand(InsertQuery, objConnection);
       objCmd.Parameters.Add("@firstname", SqlDbType.NVarChar, 10, "firstname");
       objCmd.Parameters.Add("@lastname",  SqlDbType.NVarChar, 20, "lastname");
       objAd.InsertCommand = objCmd;
       objAd.Update(objDs, "aspdotnetTable");
         } catch(Exception e) {
            Console.WriteLine("Error: " + e);
         } finally {
            objConnection.Close();
         }
      }  
   }

No comments:

Post a Comment

ASPdotNET-Example