How To Rollback A Transaction In Data Access Layer
Jul 9, 2007
Hi,
I am having a application in which from the front end i am saving details of three different things
i.Enquiry Details
ii.Parts Details
iii.Machine details
i am saving the Enquiry detail in a data table,Parts Details in a data table and machine detail in a data table and finally i am adding the three data tables into a single data set and passing the data set to data access layer there i have three insert command one for each data table in my case the enquiry data table will be saved first and then the next two details will be saved and i am saving the details in three different tables in the database, my problem is some times the enquiry details will save to the database and while saving the Parts details there may be some exception and i will throw an exception in that case the enquiry details will be saved and the remaining two details are not saved(Which are also part of the same Transaction).I wanted to know about how to call the transaction function in case of Data Access Layer.
I've been developing desktop client-server and web apps and have used Access and SQL Server Standard most of the time. I'm looking into using SQL CE, and had a few questions that I can't seem to get a clear picture on:
- The documentation for CE says that it supports 256 simultaneous connections and offers the Isolation levels, Transactions, Locking, etc with a 4GB DB. But most people say that CE is strictly a single-user DB and should not be used as a DB Server. Could CE be extended for use as a multi-user DB Server by creating a custom server such as a .NET Remoting Server hosted through a Windows Service (or any other custom host) on a machine whereby the CE DB would run in-process with this server on the machine which would then be accessed by multiple users from multiple machines?? Clients PCs -> Server PC hosting Remoting Service -> ADO.NET -> SQL CE
- and further more can we use Enterprise Services (Serviced Components) to connect to SQL CE and further extend this model to offer a pure high-quality DB Server? Clients PCs -> Server PC hosting Remoting Service -> Enterprise Services -> ADO.NET -> SQL CE
Seems quite doable to me, but I may be wrong..please let me know either ways
I've been following Soctt Mitchell's tutorials on Data Access and in Tutorial 1 (Step 5) he suggests using SQL Subqueries in TableAdapters in order to pick up extra information for display using a datasource. I have two tables for a gallery system I'm building. One called Photographs and one called MS_Photographs which has extra information about certain images. When reading the MS_Photograph data I also want to include a couple of fields from the related Photographs table. Rather than creating a table adapter just to pull this data I wanted to use the existing MS_Photographs adapter with a query such as...1 SELECT CAR_MAKE, CAR_MODEL, 2 (SELECT DATE_TAKEN 3 FROM PHOTOGRAPHS 4 WHERE (PHOTOGRAPH_ID = MS_PHOTOGRAPHS.PHOTOGRAPH_ID)) AS DATE_TAKEN, 5 (SELECT FORMAT 6 FROM PHOTOGRAPHS 7 WHERE (PHOTOGRAPH_ID = MS_PHOTOGRAPHS.PHOTOGRAPH_ID)) AS FORMAT, 8 (SELECT REFERENCE 9 FROM PHOTOGRAPHS 10 WHERE (PHOTOGRAPH_ID = MS_PHOTOGRAPHS.PHOTOGRAPH_ID)) AS REFERENCE, 11 DRIVER1, TEAM, GALLERY_ID, PHOTOGRAPH_ID 12 FROM MS_PHOTOGRAPHS 13 WHERE (GALLERY_ID = @GalleryID) This works but I wanted to know if there's a way to get all of the fields using one subquery instead of three? I did try it but it gave me errors for everything I could think of.Is using a subquery like above the best way when you want this many fields from a secondary table or should I be using another approach. I'm using classes for the BLL as well and wondered if there's a way to do it at this stage instead?
In my web application, i'm using 2 tabels; Users(Username(PK), Pwd, Name, Deptid(FK)) n Dept(Deptid(PK), Deptname)). For creating a Data Access Layer 4 my project, I added dataset as new item n followed the wizard 2 create the required functions. I have a function GetUser(@uname, @pwd), which takes username n password as input. M using this for authentication purpose. While executing it poping an ConstrainException. Plz help me out.
I've tried 2 as clear as possible here. OR u may ask me any other questions for clear picture of the scenario. Thanks and Regards, Sankar.
I request you plz tell how to create Data Access Layer. I mean DataAccess.dll. So that I can call stored procedure from dataaccess.dll as below. DataAccess.SqlHelper.ExecuteDataset(DataAccess.DSN.Connection("DBConnectionString"), CommandType.StoredProcedure, "SP_GetEmpIds"); I request you how can I add this stored procedures to DataAccess.dll and function. I am not having any idea in this area. I request you plz give me some suggestions to work with task.
HiI'm having problems following the tutorial on creating a data access layer - http://www.asp.net/learn/dataaccess/tutorial01cs.aspx?tabid=63 - when I try to compile in Visual Studio 2005 I get namespace could not be found. I followed exactly the tutorial - I created a dataset and added this code in my aspx page. <asp:GridView ID="GridView1" runat="server" CssClass="DataWebControlStyle"> <HeaderStyle CssClass="HeaderStyle" /> <AlternatingRowStyle CssClass="AlternatingRowStyle" />In my C# file I added these lines... using NorthwindTableAdapters; <<<<<this is the problem - where does this come from? protected void Page_Load(object sender, EventArgs e) { ProductsTableAdapter productsAdapter = new ProductsTableAdapter(); GridView1.DataSource = productsAdapter.GetProducts(); GridView1.DataBind(); }Thanks in advance
How do I get a System Table like 'Sysobjects' into the Data Access Layer? My app generates tables on the fly, and has to check in the sysobjects table which tables are present.
Hi Experts ! I want to use maximum feature of SQL Server 2005 and ASP.Net 2.0 in making Data Access LayerSuggestions will be welcomed .Thank you RegardsKAMRAN
I've a management module (managing Products) currently being displayed on the aspx page using ObjectDataSource and GridView control.The datasource is taken from a class residing in my Data Access layer with custom methods such as getProducts() and deleteProduct(int productID)I'm currently using SqlDataAdapter as well as Datasets to manipulate the data and have no big problems so far.However, my issue is this, each time i delete a product using the deleteProduct method, I would need to refill the dataset to fill the dataset before i can proceed to delete the product. But since I already filled the dataset using the getProducts() method, is it possible to just use that dataset again so that I dont have to make it refill again? I need to know this cos my data might be alot in the future and refilling the dataset might slow down the performance. 1 public int deleteCompany(Object companyId) 2 { 3 SqlCommand deleteCommand = new SqlCommand("DELETE FROM pg_Company WHERE CompanyId = @companyId", getSqlConnection()); 4 5 SqlParameter p1 = new SqlParameter("@companyId", SqlDbType.UniqueIdentifier); 6 p1.Value = (Guid)companyId; 7 p1.Direction = ParameterDirection.Input; 8 9 deleteCommand.Parameters.Add(p1); 10 dataAdapter.DeleteCommand = deleteCommand; 11 12 companyDS = getCompanies(); // <--- I need to refill this before I can delete, I would be iterating an empty ds. 13 14 try 15 { 16 foreach (DataRow row in companyDS.Tables["pg_Company"].Select(@"companyId = '" + companyId + "'")) 17 { 18 row.Delete(); 19 } 20 return dataAdapter.Update(companyDS.Tables["pg_Company"]); 21 } 22 catch 23 { 24 return 0; 25 } 26 finally { } 27 } I thank you in advance for any help here.
objEntites.inTest = obj.inTest;-----------------------------------------------ERROR LINE
// objEntites.Add(obj);
}
return objEntites;
}
}
}
Error 2 foreach statement cannot operate on variables of type 'System.Data.IDataReader' because 'System.Data.IDataReader' does not contain a public definition for 'GetEnumerator' D:KOTI_PRJSEnterpriseCustomerClass1.cs 34 13 Customer
I am taking my first stab at a 3 tier architecture within ASP.Net. I have been adding datasets and creating a new Insert to add certain parts to a table. I am trying to add a date field called 'DateAdded' and is setup in SQL as a DateTime. When Visual Studio auto created the dataset, the Insert function is not "DateAdded as Datetime" as I would have expected, but it is "DateAdded as System.Nullable(Of Date)". There is a space in between 'Of' and 'Date'. If I keep the space in there the insert function shows an error that says "Arguement not specified for parameter DateAdded of funtion( etc. etc.). If I take the space out, the error on the insert function goes away but there is an error within the "OfDate" that says "Array bound cannot appear in type specifiers". I am confused on why the date format changed and how I can get a date to go into the database using the autogenerated datasets from Visual Studio. Any help would be appreciated. Thanks, Mike
The query fails to execute and returns an error: String[1]: the Size property has an invalid size of 0. If I change the SqlDbType.Text parameter type to SqlDBType.Varchar, 100 (or any other fixed varchar length), it works but limits the length my unlimited field text. Any suggestions on how I can use db type text or varchar(max)? The field I need to retrieve is string characters of unlimited length and hence the datatype varchar(max).
I am working on reformating, cleaning, adding derived elements, etc... on data with no data validity checks on the front-end, source data. Its an incremental process where each month I add new data to the prior months' history. Sometimes the new monthly source data "surprises" me -- different values, different data definitons, etc. than expected.
I deal with these surprises by accumulating the fields/values that are unexpected after converting them to varchar with some explanatory language into a table [program_newdataprobs]
If there are any records in [program_newdataproblem] I rollback the transactions so the prior months' history remains unaltered. The problem is I then "lose" the contents of [program_newdataproblem] which I would like to hand to the source data people to troubleshoot.
I have tried the following:
Begin Transaction tran1
.... code that reformats data here if (select count(*) from program_newdataproblem)>0
BEGIN
Begin Transaction tran2
select * into #t1 from program_newdataproblem
Commit Transaction tran2
Rollback Transaction tran1
insert into program_newdataproblem Select * from #t1
END
This bombs because because #t1 no longer exits
Any way I can "keep" the data from program_newdataproblem when I Rollback the other transactions? (without having to store the history in separate tables that I can then access if new data errors occur)
I'm receiving the below error when trying to implement Execute SQL Task.
"The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION." This error also happens on COMMIT as well and there is a preceding Execute SQL Task with BEGIN TRANSACTION tranname WITH MARK 'tran'
I know I can change the transaction option property from "supported" to "required" however I want to mark the transaction. I was copying the way Import/Export Wizard does it however I'm unable to figure out why it works and why mine doesn't work.
I just made a transaction which writes and reads some data from a database as one unit. Now, I would like to know, what happens, if this transaction does not commit, but instead performs a rollback? Should I use a boolean loop which keeps on trying the transaction until it commits or is there an alternative? I would appreciate any suggestions or help!
If someone could help me with this I will be in debt to you!I am a .net developer who is working on a system that has a sql server2000 backend. On the weekends, I work from home and I have MSDE on mylaptop. This morning I went to update the main SQL server as I addedsome new views .. however I managed to import the data too!!Therefore I have overwritten my local data to the main sql serverdatabase, which has ressulted in loss of loads of work!Can I rollback to the version before I exported my data from MSDE to themain SQL server. I did the export by using enterprise manager and rightclicking on the table on my local msde and then sending it to the realsql server!Please please please help??*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
i have a froeach loop,in which i have data flow task,which i need to rollback if any other task fails..
here i need to accept multiple files and i have to give a one second pause for between each file for this i have used a dummy for loop,as i am using this for loop i cant give the for each loop property Transaction Option as required...but i need to rollback if any task fails...i have a screen shot of the for each loop
Hi everyone, In the following T-SQL code snippet,when I attempt to insert more than one record I encounter an error because of the following trigger but I have some doubts about the performation of ROLLBACK TRANSACTION in here. So there is only one transaction occured in the specified table that contain both trigger and the specified table however I supposed that when we call ROLLBACK TRANSACTION, the transaction is aborted. But the code run the Raiserror statement which is located in after the ROLLBACK TRANSACTION statement. So why do this code( Raiserror) is run ? Should not it be terminated because of the ROLLBACK TRANSACTION statement ??
ALTER TRIGGER kimlikNo_Degistir ON Bilgi FOR INSERT AS IF(SELECT COUNT(*) FROM Inserted) > 1 BEGIN ROLLBACK TRANSACTION RAISERROR('You are not allowed to enter more than one record',12,1) END ELSE BEGIN UPDATE M SET M.KimlikNo = B.Kimlk + M.KimlikNo FROM Muhasebe as M INNER JOIN Inserted AS B ON M.Ad = B.Ad END
I made a mistake and ran a delete query that I should not have. There have been no other transactions/modifcations to the database since my delete query.
With the function below, I receive this error:Error:Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 0.Function:Public Shared Function DeleteMesssages(ByVal UserID As String, ByVal MessageIDs As List(Of String)) As Boolean Dim bSuccess As Boolean Dim MyConnection As SqlConnection = GetConnection() Dim cmd As New SqlCommand("", MyConnection) Dim i As Integer Dim fBeginTransCalled As Boolean = False 'messagetype 1 =internal messages Try ' ' Start transaction ' MyConnection.Open() cmd.CommandText = "BEGIN TRANSACTION" cmd.ExecuteNonQuery() fBeginTransCalled = True Dim obj As Object For i = 0 To MessageIDs.Count - 1 bSuccess = False 'delete userid-message reference cmd.CommandText = "DELETE FROM tblUsersAndMessages WHERE MessageID=@MessageID AND UserID=@UserID" cmd.Parameters.Add(New SqlParameter("@UserID", UserID)) cmd.Parameters.Add(New SqlParameter("@MessageID", MessageIDs(i).ToString)) cmd.ExecuteNonQuery() 'then delete the message itself if no other user has a reference cmd.CommandText = "SELECT COUNT(*) FROM tblUsersAndMessages WHERE MessageID=@MessageID1" cmd.Parameters.Add(New SqlParameter("@MessageID1", MessageIDs(i).ToString)) obj = cmd.ExecuteScalar If ((Not (obj) Is Nothing) _ AndAlso ((TypeOf (obj) Is Integer) _ AndAlso (CType(obj, Integer) > 0))) Then 'more references exist so do not delete message Else 'this is the only reference to the message so delete it permanently cmd.CommandText = "DELETE FROM tblMessages WHERE MessageID=@MessageID2" cmd.Parameters.Add(New SqlParameter("@MessageID2", MessageIDs(i).ToString)) cmd.ExecuteNonQuery() End If Next i ' ' End transaction ' cmd.CommandText = "COMMIT TRANSACTION" cmd.ExecuteNonQuery() bSuccess = True fBeginTransCalled = False Catch ex As Exception 'LOG ERROR GlobalFunctions.ReportError("MessageDAL:DeleteMessages", ex.Message) Finally If fBeginTransCalled Then Try cmd = New SqlCommand("ROLLBACK TRANSACTION", MyConnection) cmd.ExecuteNonQuery() Catch e As System.Exception End Try End If MyConnection.Close() End Try Return bSuccess End Function
I am moving some code that was created in visual studio 2002 into Visual Web Developer 2005 express edition and am getting a warning on some of my code before compilation. The warning is "Variable lSqlTransaction is used before it has been assigned a value. A null reference exception could result at runtime". I experienced no problems in vs2002. The offending line is the rollback command within the exception. If I move it out of the exception it no longer flags the warning, if I move it after the throw statement it now longer flags the warning. Any help appreciated. Heres the code Public Shared Sub ExecuteNonQuery(ByVal lSQLCommand As SqlCommand)
Dim lSQLConnection As New SqlConnection(SQLConnString(enmSQLDB.enmSQLDB_TPSDB)) Dim lSQLTransaction As SqlTransaction
Try '----------------------------------------------------- 'Try and open the database '----------------------------------------------------- lSQLConnection.Open()
'----------------------------------------------------- 'Create a transaction '----------------------------------------------------- lSQLTransaction = lSQLConnection.BeginTransaction
'----------------------------------------------------- 'Assign the connection and transaction to our object '----------------------------------------------------- lSQLCommand.Connection = lSQLConnection lSQLCommand.Transaction = lSQLTransaction
'----------------------------------------------------- 'Execute the stored proc '----------------------------------------------------- lSQLCommand.ExecuteNonQuery()
'----------------------------------------------------- 'Use the transaction to commit the changes '----------------------------------------------------- lSQLTransaction.Commit()
Catch ex As Exception '----------------------------------------------------- 'If any errors have been thrown then roll back without 'commiting.... '----------------------------------------------------- lSQLTransaction.Rollback()
Throw New Exception("An error has occured whilst trying to update the database. " & _ "Your changes have not been saved.", ex)
Finally If lSQLConnection.State = ConnectionState.Open Then lSQLConnection.Close() End If End Try
In VB 6, using ADO, SQL Server 2000In my VB program I use the connection object (abc)to begin a transaction.abc.BeginTransI then, in my VB App, using ADO, execute multiple stored proceduresinserting records into temp tables ##Meetings,reading them, and then finnaly executing (from my VB appusing ADO) as stored procedure that inserts recordsinto a non-temp table.I then have a abc.CommitTransWhat if my VB program crashes before thecommittrans is executed, I assume that the transactionis rolled back, even though no explicit rollbackis issued, because my VB program has crashed.Thank You for your help,Laurence NuttallProgrammer Analyst IIIUCLA - Division of Continuing Education
We are loading data from one extract file in to 4 different database tables. When we are loading if the first table gets loaded without any issues and the second table loading gives any issues, we need to rollback the data loaded in to the first table also.
In the package for achieving this, we are using Sequence container. In the sequency container we are having 4 different tasks for loading data to 4 different tables from the same extract file. We also tried setting the different transaction options given in the properties box of the packages, container and tasks.
Also we tried the properties by setting as mentioned in the Test# 7 and 8 in the following URL
I have a Dataflow where I insert data from SQL to Oracle and SQL Connection needs to have RetainSameConnection = TRUE. I have Oracle Services for Microsoft Transaction Server installed and I can rollback the transaction only if SQL Connection has RetainSameConnection = FALSE and TransactionOption = Required. Is there any possibility to rollback the Oracle transaction with having SQL RetainSameConnection = TRUE and TransactionOption = Supported?
When I write code for a multiple statements transaction do I need to check 'if @@ERROR > 0 ' after each SELECT, INSERT, DELETE or UPDATE statement so that the 'rollback tran' statement can be given, or SQL server will automatically rollback the transaction and we don't need to check for @ERROR > 0 ?
Hi everyone, I am reading about the Rollback transaction but I'm not sure if it's the feature I need. My application is going to update a few tables, but my programmer said that it will be done using more than 1 transaction. For example, if I want to create a new employer with all the detailed informations, tables will be filled when the user complete the insertion of a part of data. If he decides to abort the operation, i'd like to delete all the values inserted before with the other queries. Is it possible to create a "savepoint" and roll back all transactions processed from this savepoint?
Hi,I have a problem. When my computer loses connection toserver during transaction it is rolled back automaticlyby server after 2-5 minutes. During the time a can resetmy computer, run my program again and I can seedata from not commited transaction becouse I have toset isolation level to read uncommited.How to force the server immediately rollback transaction?TIAclint