Hi
How can we define Transactions in ADO.NET?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Hemant KumarPosted Oct 12, 2011, 5:22 AM
http://www.codeproject.com/KB/database/transactions.aspx
A sample is done for you please refer this example
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TransactionDemo.aspx.cs"
Inherits="TransactionDemo" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Activities.Statements;
public partial class TransactionDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime dt = new DateTime(2011, 6, 8);
DateTime newDateTime = dt.AddMonths(2);
}
protected void btnInsert_Click(object sender, EventArgs e)
{
String connectionString = ConfigurationManager.ConnectionStrings["AdvenCON"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
//Start a local Transaction
SqlTransaction sqlTran = con.BeginTransaction();
//Enlist a command in the current Transaction
SqlCommand cmd = con.CreateCommand();
cmd.Transaction = sqlTran;
try
{
//One way of writing Insert Query
// Execute two Separate Commands
//cmd.CommandText = "INSERT INTO PRODUCTION.SCRAPREASON(Name) VALUES(@Name1)";
//cmd.Parameters.AddWithValue("@Name1", tbName1.Text);
//cmd.ExecuteNonQuery();
//cmd.CommandText = "INSERT INTO PRODUCTION.SCRAPREASON(Name) VALUES(@Name2)";
//cmd.Parameters.AddWithValue("@Name2", tbName2.Text);
//cmd.ExecuteNonQuery();
//Second way of writing Insert Query
new SqlCommand(String.Format("INSERT INTO PRODUCTION.SCRAPREASON(Name) VALUES('{0}')", tbName1.Text), con, sqlTran).ExecuteNonQuery();
new SqlCommand(String.Format("INSERT INTO PRODUCTION.SCRAPREASON(Name) VALUES('{0}')", tbName2.Text), con, sqlTran).ExecuteNonQuery();
//Commit the Transaction
sqlTran.Commit();
divMessage.InnerText = "Records inserted Successfully!";
}
catch (Exception expSqlTransaction)
{
//Handle the exception if the transaction fails to Commit
divMessage.InnerText = expSqlTransaction.Message;
try
{
sqlTran.Rollback();
}
catch (Exception exRollback)
{
divMessage.InnerText = exRollback.Message;
}
}
}
}
}
Hope this will help you :-)
Prabhu RajaPosted Oct 10, 2011, 2:24 PM
You can get a dozens of Articles written by our own Network Authors.
Use this Link:
http://www.c-sharpcorner.com/Search/?sKeywords=Transactions+in+ADO.NET
Suthish NairPosted Oct 10, 2011, 1:35 PM
Javeed M ShaikhPosted Oct 10, 2011, 12:52 PM
Here is an example:
Please do not forget to mark "Accepted Answer".