Thursday, May 19, 2011

Way of Insert Data in Database Table with ADO.Net

There are many way Insert data in database table.
I described Five way here.
1. using sql command techniques insert data into database table 
2.Using Bind parameters sql command techniques insert data into database table 
3.using sql command with Parameters techniques insert data into database table 
4.Using ExecuteScalar and SqlCommand Insert data into Database Table 
5.using CommandBuilder insert datat in form datatable in datadase 
5 is Best and Optimize way of insert data into database table because in with 
using conncetionless (SqlDataAdpter) concepts and in insert in datatable form so 
it is best in Performance view and it can use with asp.net where large amount of
users are working.  

using CommandBuilder insert datat in form datatable in datadase

This is the best and optimize way of insert data in to database table 
with ado.net
InsertingDataUsingCommandBuilder
using System;
using System.Data;
using System.Data.SqlClient;

public class InsertingDataUsingCommandBuilder
{
 
static void Main(string[] args)
 {
string Cn="DataSource=(local);InitialCatalog=CaseManager;Integrated Security=true";
string Query="SELECT ID, Contact, Email FROM Test";
SqlConnection objConnection = new SqlConnection(Cn);
SqlDataAdapter objDataAdapter = new SqlDataAdapter(Query,objConnection);
SqlCommandBuilder objCmd = new SqlCommandBuilder(objDataAdapter);
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet);
DataRow objRow = objDataSet.Tables[0].NewRow();
objRow["ID"] = 520;
objRow["Contact"] = "Bill";
objRow["Email"] = "Ray";
objDataSet.Tables[0].Rows.Add(objRow);
objDataAdapter.Update(objDataSet);
        }
    }

Using ExecuteScalar and SqlCommand Insert data into Database Table

using System;

using System.Data;

using System.Data.SqlClient;
   

public class InsertingDataUsingSQLStatementsExecuteScalar

{

static void Main(string[] args)

{
string CN="Data Source=(local); Initial Catalog = DBNAME; Integrated Security=true; 
SqlConnection objConnection = new SqlConnection(CN);
            

String Query ="INSERT INTO tblTest(ID, Contact, Email) VALUES(3, 'Bill', 'John')";

SqlCommand objCmd = new SqlCommand(Query, onConnection);objConnection.Open();
objCmd.ExecuteScalar();
objConnection.Close();

} 
}


using sql command with Parameters techniques insert data into database table

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

class UsingParameterAndCommand
 {
    public static void Main() 
{
string cn="server=localhost;database=DBTEST;uid=sa;pwd=sa";
 SqlConnection Connection = new SqlConnection(cn);
        
        SqlCommand objCmd = Connection.CreateCommand();
        objCmd.CommandText =
          "INSERT INTO ASPTable (" +
          "  CustomerID, CompanyName, ContactName" +
          ") VALUES (" +
          "  @CustomerID, @CompanyName, @ContactName" +
          ")";
        objCmd.Parameters.Add("@CustomerID", "AB001");
        objCmd.Parameters.Add("@CompanyName", "MicroSoft");
        objCmd.Parameters.Add("@ContactName", "Bill");
        Connection.Open();
        objCmd.ExecuteNonQuery();
        Console.WriteLine("Successfully added row to ASPTable ");

        Connection.Close();
    }
}

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();
         }
      }  
   }

using sql command techniques insert data into database table

we must add using System.Data.SqlClient; namespace. 
now following code you can use.
This is Vary old Techniques. If we use techniques with Asp.net 
there is Pooling required because if there is large amount of users 
use this page than it is difficult to handle connnection.  
Insert into database using sqlcommand 
using System;
using System.Data;
using System.Data.SqlClient;

   class sqlcommandexample
{
      static void Main() 
      {
string CN="server=(local)\\SQLEXPRESS;database=DBTEST;Integrated Security=SSPI"; 
SqlConnection objCn = new SqlConnection(CN);
         SqlCommand objCmd= objCn.CreateCommand();

         try 
         {
objCn.Open();

objCmd.CommandText = "CREATE DATABASE NewDB";
Console.WriteLine(objCmd.CommandText);

objCmd.ExecuteNonQuery();
Console.WriteLine("Now is Database created and database");
objCn.ChangeDatabase("NewDB");

objCmd.CommandText = "CREATE TABLE aspdotnetTable(COL1 integer)";
Console.WriteLine(objCmd.CommandText);
Console.WriteLine("NO Rows Affected is: {0}", objCmd.ExecuteNonQuery());

objCmd.CommandText = "INSERT INTO aspdotnetTable VALUES (100)";
Console.WriteLine(objCmd.CommandText);
Console.WriteLine("NO Rows Affected is: {0}", objCmd.ExecuteNonQuery());
         
         } catch (SqlException ex) {
         
            Console.WriteLine(ex.ToString());
         
         } finally {  
         
            objCn.Close();
            Console.WriteLine("Connection Closed.");
         
         }
      }
   }
ASPdotNET-Example