Home  »  Articles  »  C#.Net  »

How to insert values into two tables of SQL Server 2005 using C#.Net?

 Posted By : Manoj SahooPosted Date : 25/10/2010 07:34:42 AM Category : C#.Net Points : 5 (Rs 2.00)

We can insert values into two tables by using below code :

string strsql="insert into Table1 (fname,lname,dob) Values('FirstName','LastName','01/01/1982');insert into Table2 (age,address,city) Values(25,'Address Value','City Name')";
UpdatedCommand(strsql);

To use sql client features, we have to import SqlClient namespace. So use below :

using System.Data.SqlClient;

 


Use Below code to update :

public int UpdatedCommand(string strupdatequery)
{
SqlTransaction transsql;
SqlConnection sqlconn;
sqlconn = new SqlConnection("Your Connection String");
int intreturn = -4;
try
{
SqlCommand cmdupdatecommand = new SqlCommand();
transsql = null;
if (sqlconn.State != ConnectionState.Open)
{
sqlconn.Open();
}
transsql = sqlconn.BeginTransaction();
cmdupdatecommand.CommandTimeout = 0;
cmdupdatecommand.CommandText = strupdatequery;
cmdupdatecommand.Connection = sqlconn;
cmdupdatecommand.Transaction = transsql;
intreturn = cmdupdatecommand.ExecuteNonQuery();
transsql.Commit();
if (sqlconn.State != ConnectionState.Closed)
{
sqlconn.Close();
}
return intreturn;
}
catch (SqlException oleex)
{
transsql.Rollback();
strupdatequery = oleex.Message;
return -3;
}
catch (System.Exception exp)
{
transsql.Rollback();
strupdatequery = exp.Message;
return -3;
}
finally
{
if (sqlconn.State != ConnectionState.Closed){sqlconn.Close();}
}
}

Thank You.

Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.