Search Results

Search found 29 results on 2 pages for 'sqltransaction'.

Page 1/2 | 1 2  | Next Page >

  • CommandBuilder and SqlTransaction to insert/update a row

    - by Jesse
    I can get this to work, but I feel as though I'm not doing it properly. The first time this runs, it works as intended, and a new row is inserted where "thisField" contains "doesntExist" However, if I run it a subsequent time, I get a run-time error that I can't insert a duplicate key as it violate the primary key "thisField". static void Main(string[] args) { using(var sqlConn = new SqlConnection(connString) ) { sqlConn.Open(); var dt = new DataTable(); var sqlda = new SqlDataAdapter("SELECT * FROM table WHERE thisField ='doesntExist'", sqlConn); sqlda.Fill(dt); DataRow dr = dt.NewRow(); dr["thisField"] = "doesntExist"; //Primary key dt.Rows.Add(dr); //dt.AcceptChanges(); //I thought this may fix the problem. It didn't. var sqlTrans = sqlConn.BeginTransaction(); try { sqlda.SelectCommand = new SqlCommand("SELECT * FROM table WITH (HOLDLOCK, ROWLOCK) WHERE thisField = 'doesntExist'", sqlConn, sqlTrans); SqlCommandBuilder sqlCb = new SqlCommandBuilder(sqlda); sqlda.InsertCommand = sqlCb.GetInsertCommand(); sqlda.InsertCommand.Transaction = sqlTrans; sqlda.DeleteCommand = sqlCb.GetDeleteCommand(); sqlda.DeleteCommand.Transaction = sqlTrans; sqlda.UpdateCommand = sqlCb.GetUpdateCommand(); sqlda.UpdateCommand.Transaction = sqlTrans; sqlda.Update(dt); sqlTrans.Commit(); } catch (Exception) { //... } } } Even when I can get that working through trial and error of moving AcceptChanges around, or encapsulating changes within Begin/EndEdit, then I begin to experience a "Concurrency violation" in which it won't update the changes, but rather tell me it failed to update 0 of 1 affected rows. Is there something crazy obvious I'm missing?

    Read the article

  • C# - Rollback SqlTransaction in catch block - Problem with object accessability

    - by Marks
    Hi there. I've got a problem, and all articles or examples i found seem to not care about it. I want to do some database actions in a transaction. What i want to do is very similar to most examples: using (SqlConnection Conn = new SqlConnection(_ConnectionString)) { try { Conn.Open(); SqlTransaction Trans = Conn.BeginTransaction(); using (SqlCommand Com = new SqlCommand(ComText, Conn)) { /* DB work */ } } catch (Exception Ex) { Trans.Rollback(); return -1; } } But the problem is, that the SqlTransaction Trans is declared inside the try block. So it is not accessable in the catch() block. Most examples just do Conn.Open() and Conn.BeginTransaction() before the try block. But i think thats a bit risky, since both can throw multiple exceptions. Am I wrong, or do most people just ignore this risk? Whats the best solution to be able to rollback, if an exception happens. Thanks in advance, Marks

    Read the article

  • Refactoring ADO.NET - SqlTransaction vs. TransactionScope

    - by marc_s
    I have "inherited" a little C# method that creates an ADO.NET SqlCommand object and loops over a list of items to be saved to the database (SQL Server 2005). Right now, the traditional SqlConnection/SqlCommand approach is used, and to make sure everything works, the two steps (delete old entries, then insert new ones) are wrapped into an ADO.NET SqlTransaction. using (SqlConnection _con = new SqlConnection(_connectionString)) { using (SqlTransaction _tran = _con.BeginTransaction()) { try { SqlCommand _deleteOld = new SqlCommand(......., _con); _deleteOld.Transaction = _tran; _deleteOld.Parameters.AddWithValue("@ID", 5); _con.Open(); _deleteOld.ExecuteNonQuery(); SqlCommand _insertCmd = new SqlCommand(......, _con); _insertCmd.Transaction = _tran; // add parameters to _insertCmd foreach (Item item in listOfItem) { _insertCmd.ExecuteNonQuery(); } _tran.Commit(); _con.Close(); } catch (Exception ex) { // log exception _tran.Rollback(); throw; } } } Now, I've been reading a lot about the .NET TransactionScope class lately, and I was wondering, what's the preferred approach here? Would I gain anything (readibility, speed, reliability) by switching to using using (TransactionScope _scope = new TransactionScope()) { using (SqlConnection _con = new SqlConnection(_connectionString)) { .... } _scope.Complete(); } What you would prefer, and why? Marc

    Read the article

  • SQL SERVER - Understanding how MIN(text) works.

    - by tmercer
    I'm doing a little digging and looking for a explanation on how SQL server evaluates MIN(Varchar). I found this remark in BOL: MIN finds the lowest value in the collating sequence defined in the underlying database So if I have a table that has one row with the following values: Data AA AB AC Doing a SELECT MIN(DATA) would return back AA. I just want to understand the why behind this and understand the BOL a little better. Thanks!

    Read the article

  • How do you check individual SqlCommands ran during a SqlTransactions to see if they will run?

    - by Sam F
    I've been reading up on SqlTransactions and have found a great load of examples like: http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=451 The problem is, when I do a BeginTransaction() (Execute all the commands) and then Commit() at the end all the commands I execute get run and the ones with syntax errors or other errors just get skipped. This is where I would also like to run a roll back, not skip over them. I found a few articles on the subject but they were not very helpful and purely in SQL. Is there any way to find out if one of the ExecuteNonQuery()'s failed before the commit and not just skipped? Thanks.

    Read the article

  • TransactionScope and Transactions

    - by Mike
    In my C# code I am using TransactionScope because I was told not to rely that my sql programmers will always use transactions and we are responsible and yada yada. Having said that It looks like TransactionScope object Rolls back before the SqlTransaction? Is that possible and if so what is the correct methodology for wrapping a TransactionScope in a transaction. Here is the sql test CREATE PROC ThrowError AS BEGIN TRANSACTION --SqlTransaction SELECT 1/0 IF @@ERROR<> 0 BEGIN ROLLBACK TRANSACTION --SqlTransaction RETURN -1 END ELSE BEGIN COMMIT TRANSACTION --SqlTransaction RETURN 0 END go DECLARE @RESULT INT EXEC @RESULT = ThrowError SELECT @RESULT And if I run this I get just the divide by 0 and return -1 Call from the C# code I get an extra error message Divide by zero error encountered. Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION tatement is missing. Previous count = 1, current count = 0. If I give the sql transaction a name then Cannot roll back SqlTransaction. No transaction or savepoint of that name was found. Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 2. some times it seems the count goes up, until the app completely exits The c# is just using (TransactionScope scope = new TransactionScope()) { ... Execute Sql scope.Commit() }

    Read the article

  • How to add root node in the output method = text

    - by Akhil
    My sample input is <?xml version="1.0" encoding="UTF-8"?> <ns0:JDBC_RECEIVERDATA_MT_response xmlns:ns0="urn:parmalat.com.au:TESTSQL_REPLICATION"> <Statement_response> <response_1> <row> <XML_F52E2B61-18A1-11d1-B105-00805F49916B><![CDATA[<TransactionLog TID="1400" SeqNo="3337446" SQLTransaction="Insert into TankerLoads Values(141221,53,299,18,1,426148,6,&apos;Nov 19 2007 12:00AM&apos;,&apos;Dec 30 1899 12:59PM&apos;,3.00,20682,0,&apos;Zevo&apos;,&apos;Nov 19 2007 12:00AM&apos;,0)"/></row> <row> <XML_F52E2B61-18A1-11d1-B105-00805F49916B>um = 141221"/&gt;&lt;TransactionLog TID="1400" SeqNo="3337452" SQLTransaction="Insert into MilkPickups Values(790195,141221,0,&amp;apos;Nov 19 2007 12:00AM&amp;apos;,2433,&amp;apos;Nov 19 2007 12:00AM&amp;apos;,&amp;apos;Dec 30 1899 11:26AM&amp;apos;,3131,2.90)"/&gt; Like this I have mutiple records and my output should be like <root> <TransactionLog TID="1400" SeqNo="3337446" SQLTransaction="Insert into TankerLoads Values(141221,53,299,18,1,426148,6,'Nov 19 2007 12:00AM','Dec 30 1899 12:59PM',3.00,20682,0,'Zevo','Nov 19 2007 12:00AM',0)" /> <TransactionLog TID="1400" SeqNo="3337447" SQLTransaction="Update TankerLoads Set TankerNum = 53,DriverNum = 299,CarterNum = 18,MilkTypeNum = 1,SampleNum = 426148,ReceivalBayNum = 6,UnloadDate = 'Nov 19 2007 12:00AM',UnloadTime = 'Dec 30 1899 12:59PM',Temperature = 3.00,Volume = 20682,NetWeight = 0,WeighbridgeDocket = 'Zevo',LoadPickupDate = 'Nov 19 2007 12:00AM',IsValidated = 0 Where TankerLoadNum = 141221" /></root> AND I AM USING OUTPUT METHOD AS TEXT BECAUSE IF I USE XML THE TAG ARE REPLACED WITH &LT &GT WHICH I DONT MOREOVER IF YOU SEE THE ABOVE TWO ROWS THE LAST LINE IS HALF THE RECORD IS IN THE FIRST ROW AND CONTINUING THE OTHER HALF IN THE SECOND ROW SO i USED WHICH LEAVES SINGLE SPACE SO EVEN I DONT WANT THAT SINGLE SPACE..I HOPE I AM CLEAR IF NOT PLEASE LET ME KNOW I WILL ADD MORE COMMENTS..TPLEASE HELP ME OUT..THNKYOU

    Read the article

  • How to catch exception on RollBack

    - by Jagd
    What is the best way to implement error handling for a SqlTransaction RollBack that already exists within a catch clause? My code is roughly like this: using (SqlConnection objSqlConn = new SqlConnection(connStr)) { objSqlConn.Open(); using (SqlTransaction objSqlTrans = objSqlConn.BeginTransaction()) { try { // code // more code // and more code } catch (Exception ex) { // What happens if RollBack() has an exception? objSqlTrans.Rollback(); throw ex; } } } I believe that my application had an exception in the try block, which in turn was caught in the catch block and then the RollBack was attempted. However, the error that I'm seeing says something about a SqlTransaction.ZombieCheck(), which is making me wonder if the RollBack() itself threw an exception as well. So, do I need to implement some type of error handling at the RollBack()? How do I do that and manage to hold on to the exception that put the execution into the catch block in the first place?

    Read the article

  • How to use SQL file streaming win32 API and support WCF streaming

    - by Mahesh
    I'm using Sql server file stream type to store large files in the backend. I'm trying to use WCf to stream the file across to the clients. I'm able to get the handle to the file using SQLFileStream (API). I then try to return this stream. I have implemenetd data chunking on the client side to retrive the data from the stream. I'm able to do it for regular filestream and memory stream. Also if i convert then sqlfilestream in to memorystream that also works. The only think that doesn't work is when I try to return sqlfilestream. What am I doing wrong. I have tried both nettcpbinding with streaming enabled and http binding with MTOM encoding. This is the error message am getting : Socket connection was aborted. This could be caused by an error processing your mesage or a receive timeout being exceeded by the remote host, or an underlying network issue.. Local socket timneout was 00:09:59.... Here is my sample code RemoteFileInfo info = new RemoteFileInfo(); info.FileName = "SampleXMLFileService.xml"; string pathName = DataAccess.GetDataSnapshotPath("DataSnapshot1"); SqlConnection connection = DataAccess.GetConnection(); SqlTransaction sqlTransaction = connection.BeginTransaction("SQLSileStreamingTrans"); SqlCommand command = new SqlCommand(); command.Connection = connection; command.Transaction = sqlTransaction; command.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()"; byte[] transcationContext = command.ExecuteScalar() as byte[]; SqlFileStream stream = new SqlFileStream(pathName, transcationContext, FileAccess.Read); // byte[] bytes = new byte[stream.Length]; // stream.Read(bytes, 0, (int) stream.Length); // Stream reeturnStream = stream; // MemoryStream memoryStream = new MemoryStream(bytes); info.FileByteStream = stream; info.Length = info.FileByteStream.Length; connection.Close(); return info; [MessageContract] public class RemoteFileInfo : IDisposable { [MessageHeader(MustUnderstand = true)] public string FileName; [MessageHeader(MustUnderstand = true)] public long Length; [MessageBodyMember(Order = 1)] public System.IO.Stream FileByteStream; public void Dispose() { if (FileByteStream != null) { FileByteStream.Close(); FileByteStream = null; } } } ANy help is appreciated

    Read the article

  • SQL Command Result to Dictionary C# .NET 2.0

    - by Joel
    I have a simple SQL query (using SqlCommand, SqlTransaction) in .NET 2.0 that returns a table of integer-string pairs (ID, Name). I want to get this data into a dictionary like Dictionary. I can get the result into a DataTable, but even iterating over it, I'm not sure how to do the typing and all that stuff. I feel like this must be a common problem but I haven't found any good solutions. Thanks in advance.

    Read the article

  • Update transaction in SQL Server 2008 R2 from ASP.Net not working

    - by Amarus
    Hello! Even though I've been a stalker here for ages, this is the first post I'm making. Hopefully, it won't end here and more optimistically future posts might actually be me trying to give a hand to someone else, I do owe this community that much and more. Now, what I'm trying to do is simple and most probably the reason behind it not working is my own stupidity. However, I'm stumped here. I'm working on an ASP.Net website that interacts with an SQL Server 2008 R2 database. So far everything has been going okay but updating a row (or more) just won't work. I even tried copying and pasting code from this site and others but it's always the same thing. In short: No exception or errors are shown when the update command executes (it even gives the correct count of affected rows) but no changes are actually made on the database. Here's a simplified version of my code (the original had more commands and tons of parameters each, but even when it's like this it doesn't work): protected void btSubmit_Click(object sender, EventArgs e) { using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString)) { string commandString = "UPDATE [impoundLotAlpha].[dbo].[Vehicle]" + "SET [VehicleMake] = @VehicleMake" + " WHERE [ComplaintID] = @ComplaintID"; using (SqlCommand command = new SqlCommand(commandString, connection)) { SqlTransaction transaction = null; try { command.Connection.Open(); transaction = connection.BeginTransaction(IsolationLevel.Serializable); command.Transaction = transaction; SqlParameter complaintID = new SqlParameter("@complaintID", SqlDbType.Int); complaintID.Value = HttpContext.Current.Request.QueryString["complaintID"]; command.Parameters.Add(complaintID); SqlParameter VehicleMake = new SqlParameter("@VehicleMake", SqlDbType.VarChar, 20); VehicleMake.Value = tbVehicleMake.Text; command.Parameters.Add(VehicleMake); command.ExecuteNonQuery(); transaction.Commit(); } catch { transaction.Rollback(); throw; } finally { connection.Close(); } } } } I've tried this with the "SqlTransaction" stuff and without it and nothing changes. Also, since I'm doing multiple updates at once, I want to have them act as a single transaction. I've found that it can be either done like this or by use of the classes included in the System.Transactions namespace (CommittableTransaction, TransactionScope...). I tried all I could find but didn't get any different results. The connection string in web.config is as follows: <connectionStrings> <add name="ApplicationServices" connectionString="Data Source=localhost;Initial Catalog=ImpoundLotAlpha;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings> So, tldr; version: What is the mistake that I did with that record update attempt? (Figured it out, check below if you're having a similar issue.) What is the best method to gather multiple update commands as a single transaction? Thanks in advance for any kind of help and/or suggestions! Edit: It seems that I was lacking some sleep yesterday cause this time it only took me 5 minutes to figure out my mistake. Apparently the update was working properly but I failed to notice that the textbox values were being overwritten in Page_Load. For some reason I had this part commented: if (IsPostBack) return; The second part of the question still stands. But should I post this as an answer to my own question or keep it like this?

    Read the article

  • Protecting against transaction concurency (Transaction type; Transaction IsolationLevel)

    - by Vytas999
    Middle-tier component will execute the data access routines in application. The component will call several SQL Server stored procedures to perform database updates. All of these procedure calls run under the control of a single transaction. The code for the middle-tier will implement the following objects: SqlCommand comm = connection.CreateCommand(); SqlTransaction trans; How i must add code to component to specify the highest possible level of protection against such errors(two users try to update the same data concurrently).

    Read the article

  • SqlCommand() ExecuteNonQuery() truncates command text.

    - by H. Abraham Chavez
    I'm building a custom db deployment utility, I need to read text files containing sql scripts and execute them against the database. Pretty easy stuff, so far so good. However I've encountered a snag, the contents of the file are read successfully and entirely, but once passed into the SqlCommand and then executed with SqlCommand.ExecuteNonQuery only part of the script is executed. I fired up Profiler and confirmed that my code is not passing all of the script. private void ExecuteScript(string cmd, SqlConnection sqlConn, SqlTransaction trans) { SqlCommand sqlCmd = new SqlCommand(cmd, sqlConn, trans); sqlCmd.CommandType = CommandType.Text; sqlCmd.CommandTimeout = 9000000; // for testing sqlCmd.ExecuteNonQuery(); } // I call it like this, readDMLScript contains 543 lines of T-SQL string readDMLScript = ReadFile(dmlFile); ExecuteScript(readDMLScript, sqlConn, trans);

    Read the article

  • How does rolling back an application level transaction interact with SqlDataAdapter events in ADO.NE

    - by ilasno
    When utilizing the RowUpdated event in the SqlAdapter class, i'm assuming that it is raised directly following the return of the database interaction that executes the update. If that update is part of an application level transaction (utilizing the SqlTransaction class) which is then rolled back, does this affect or interact at all with the RowUpdated event? Or is the RowUpdated event not raised until after the transaction is committed (this seems unlikely, but i couldn't find documentation)? If RowUpdated has already been raised, and then the transaction is rolled back, any good ideas on how to adjust something that may have been done in RowUpdated that should then, also be rolled back?

    Read the article

  • Is there a difference SMO ServerConnection transaction methods versus using the SqlConnectionObject

    - by YWE
    I am using SMO to create databases and tables on a SQL Server. I want to do so in a transaction. Are both of these methods of doing so valid and equivalent: First method: Server server; //... server.ConnectionContext.BeginTransaction(); //... server.ConnectionContext.CommitTransaction(); Second method: Server server; // ... SqlConnection conn = server.ConnectionContext.SqlConnectionObject; SqlTransaction trans = conn.BeginTransaction(); // ... trans.Commit();

    Read the article

  • How to add Transactions with a DataSet created using the Add Connection Wizard?

    - by RoguePlanetoid
    I have a DataSet that I have added to my project where I can Insert and Add records using the Add Query function in Visual Studio 2010, however I want to add transactions to this, I have found a few examples but cannot seem to find one that works with these. I know I need to use the SQLClient.SQLTransaction Class somehow. I used the Add New Data Source Wizard and added the Tables/View/Functions I need, I just need an example using this process such as How to get the DataConnection my DataSet has used. Assuming all options have been set in the wizard and I am only using the pre-defined adapters and options asked for in this wizard, how to I add the Transaction logic to my Database. For example I have a DataSet called ProductDataSet with the XSD created for this, I have then added my Stock table as a Datasource and Added an AddStock method with a wizard, this also if a new item calls an AddItem method, if either of these fails I want to rollback the AddItem and AddStock in this case.

    Read the article

  • Accessing FILESTREAM from an SQL CLR assembly

    - by superware
    I'm trying to stream FILESTREAM data from an unsafe SQL CLR assembly. The connection string is Data Source=LAPTOP2\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Enlist=False When creating a new SqlFileStream (inside a SqlTransaction, of course), I'm getting: The request is not supported at OpenSqlFilestream. So I decided to try native OpenSqlFilestream, but then I'm getting an invalid handle (-1) while GetLastWin32Error returns that same: The request is not supported (ERROR_NOT_SUPPORTED). I have also tried SqlContext.WindowsIdentity.Impersonate() with no apparent effect. I couldn't find any documentation referencing this restriction. Is it really unsupported? If it is unsupported, is there a good reason? Does anyone know of a workaround?

    Read the article

  • What purpose does “using” serve when used the following way

    - by user287745
    What purpose does “using” serve when used the following way:- ONE EXAMPLE IS THIS, (AN ANSWERER- @richj - USED THIS CODE TO SOLVE A PROBLEM THANKS) private Method(SqlConnection connection) { using (SqlTransaction transaction = connection.BeginTransaction()) { try { // Use the connection here .... transaction.Commit(); } catch { transaction.Rollback(); throw; } } } OTHER EXAMPLE I FOUND WHILE READING ON MICROSOFT SUPPORT SITE public static void ShowSqlException(string connectionString) { string queryString = "EXECUTE NonExistantStoredProcedure"; StringBuilder errorMessages = new StringBuilder(); using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); try { command.Connection.Open(); command.ExecuteNonQuery(); } catch (SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } Console.WriteLine(errorMessages.ToString()); } } } I AM doing at top of page as using system.data.sqlclient etc so why this using thing in middle of code, What if I omit it (I know the code will work) but what functionality will I be losing

    Read the article

  • SQL Server 2000 intermittent connection exceptions on production server - specific environment probl

    - by StickyMcGinty
    We've been having intermittent problems causing users to be forcibly logged out of out application. Our set-up is ASP.Net/C# web application on Windows Server 2003 Standard Edition with SQL Server 2000 on the back end. We've recently performed a major product upgrade on our client's VMWare server (we have a guest instance dedicated to us) and whereas we had none of these issues with the previous release the added complexity that the new upgrade brings to the product has caused a lot of issues. We are also running SQL Server 2000 (build 8.00.2039, or SP4) and the IIS/ASP.NET (.Net v2.0.50727) application on the same box and connecting to each other via a TCP/IP connection. Primarily, the exceptions being thrown are: System.IndexOutOfRangeException: Cannot find table 0. System.ArgumentException: Column 'password' does not belong to table Table. [This exception occurs in the log in script, even though there is clearly a password column available] System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first. [This one is occurring very regularly] System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable. System.ApplicationException: ExecuteReader requires an open and available Connection. The connection's current state is connecting. System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. And just today, for the first time: System.Web.UI.ViewStateException: Invalid viewstate. We have load tested the app using the same number of concurrent users as the production server and cannot reproduce these errors. They are very intermittent and occur even when there are only 8/9/10 user connections. My gut is telling me its ASP.NET - SQL Server 2000 connection issues.. We've pretty much ruled out code-level Data Access Layer errors at this stage (we've a development team of 15 experienced developers working on this) so we think its a specific production server environment issue.

    Read the article

  • Getting identity from Ado.Net Update command

    - by rboarman
    My scenario is simple. I am trying to persist a DataSet and have the identity column filled in so I can add child records. Here's what I've got so far: using (SqlConnection connection = new SqlConnection(connStr)) { SqlDataAdapter adapter = new SqlDataAdapter("select * from assets where 0 = 1", connection); adapter.MissingMappingAction = MissingMappingAction.Passthrough; adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; SqlCommandBuilder cb = new SqlCommandBuilder(adapter); var insertCmd = cb.GetInsertCommand(true); insertCmd.Connection = connection; connection.Open(); adapter.InsertCommand = insertCmd; adapter.InsertCommand.CommandText += "; set ? = SCOPE_IDENTITY()"; adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters; var param = new SqlParameter("RowId", SqlDbType.Int); param.SourceColumn = "RowId"; param.Direction = ParameterDirection.Output; adapter.InsertCommand.Parameters.Add(param); SqlTransaction transaction = connection.BeginTransaction(); insertCmd.Transaction = transaction; try { assetsImported = adapter.Update(dataSet.Tables["Assets"]); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); // Log an error } connection.Close(); } The first thing that I noticed, besides the fact that the identity value is not making its way back into the DataSet, is that my change to add the scope_identity select statement to the insert command is not being executed. Looking at the query using Profiler, I do not see my addition to the insert command. Questions: 1) Why is my addition to the insert command not making its way to the sql being executed on the database? 2) Is there a simpler way to have my DataSet refreshed with the identity values of the inserted rows? 3) Should I use the OnRowUpdated callback to add my child records? My plan was to loop through the rows after the Update() call and add children as needed. Thank you in advance. Rick

    Read the article

  • Insert records using ExecuteNonQuery, showing exception that invalid column name

    - by tina
    Hi all, I am using SQL Server 2008. I want to insert records into a table using ExecuteNonQuery, for that I have written: customUtility.ExecuteNonQuery("insert into furniture_ProductAccessories(Product_id, Accessories_id, SkuNo, Description1, Price, Discount) values(" + prodid + "," + strAcc + "," + txtSKUNo.Text + "," + txtAccDesc.Text + "," + txtAccPrices.Text + "," + txtAccDiscount.Text + ")"); & following is ExecuteNonQuery function: public static bool ExecuteNonQuery(string SQL) { bool retVal = false; using (SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["dbConnect"].ToString())) { con.Open(); SqlTransaction trans = con.BeginTransaction(); SqlCommand command = new SqlCommand(SQL, con, trans); try { command.ExecuteNonQuery(); trans.Commit(); retVal = true; } catch(Exception ex) { //HttpContext.Current.Response.Write(SQL + "<br>" + ex.Message); //HttpContext.Current.Response.End(); } finally { // Always call Close when done reading. con.Close(); } return retVal; } } but it showing exception that invalid column name to Description1 and even it's value which coming from txtAccDesc.Text. I have tried by removing Description1 column, other records are getting inserted successfully. Could you please help me? Thanks.

    Read the article

  • TransactionScope question - how can I keep the DTC from getting involved in this?

    - by larryq
    (I know the circumstances surrounding the DTC and promoting a transaction can be a bit mysterious to those of us not in the know, but let me show you how my company is doing things, and if you can tell me why the DTC is getting involved, and if possible, what I can do to avoid it, I'd be grateful.) I have code running on an ASP.Net webserver. We have one database, SQL 2008. Our data access code looks something like this-- We have a data access layer that uses a wrapper object for SQLConnections and SQLCommands. Typical use looks like this: void method1() { objDataObject = new DataAccessLayer(); objDataObject.Connection = SomeConnectionMethod(); SqlCommand objCommand = DataAccessUtils.CreateCommand(SomeStoredProc); //create some SqlParameters, add them to the objCommand, etc.... objDataObject.BeginTransaction(IsolationLevel.ReadCommitted); objDataObject.ExecuteNonQuery(objCommand); objDataObject.CommitTransaction(); objDataObject.CloseConnection(); } So indeed, a very thin wrapper around SqlClient, SqlConnection etc. I want to run several stored procs in a transaction, and the wrapper class doesn't allow me access to the SqlTransaction so I can't pass it from one component to the next. This led me to use a TransactionScope: using (TransactionScope tx1 = new TransactionScope(TransactionScope.RequiresNew)) { method1(); method2(); method3(); tx1.Complete(); } When I do this, the DTC gets involved, and unfortunately our webservers don't have "allow remote clients" enabled in the MSDTC settings-- getting IT to allow that will be a fight. I'd love to avoid DTC becoming involved but can I do it? Can I leave out the transactional calls in methods1-3() and just let the TransactionScope figure it all out?

    Read the article

  • ASP.NET, C#: timeout when trying to Transaction.Commit() to database; potential deadlock?

    - by user1843921
    I have a web page that has coding structured somewhat as follows: SqlConnection conX =new SqlConnection(blablabla); conX.Open(); SqlTransaction tran=conX.BeginTransaction(); try{ SqlCommand cmdInsert =new SqlCommand("INSERT INTO Table1(ColX,ColY) VALUES @x,@y",conX); cmdInsert.Transaction=tran; cmdInsert.ExecuteNonQuery(); SqlCommand cmdSelect=new SqlCOmmand("SELECT * FROM Table1",conX); cmdSelect.Transaction=tran; SqlDataReader dtr=cmdSelect.ExecuteReader(); //read stuff from dtr dtr.Close(); cmdInsert=new SqlCommand("UPDATE Table2 set ColA=@a",conX); cmdInsert.Transaction=tran; cmdInsert.ExecuteNonQuery(); //display MiscMessage tran.Commit(); //display SuccessMessage } catch(Exception x) { tran.Rollback(); //display x.Message } finally { conX.Close(); } So, everything seems to work until MiscMessage. Then, after a while (maybe 15-ish seconds?) x.Message pops up, saying that: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." So something wrong with my trans.Commit()? The database is not updated so I assume the trans.Rollback works... I have read that deadlocks can cause timeouts...is this problem cause by my SELECT statement selecting from Table1, which is being used by the first INSERT statement? If so, what should I do? If that ain't the problem, what is?

    Read the article

  • transaction handling in dataset based insert/update in c#

    - by user3703611
    I am trying to insert bulk records in a sql server database table using dataset. But i am unable to do transaction handling. Please help me to apply transaction handling in below code. I am using adapter.UpdateCommand.Transaction = trans; but this line give me an error of Object reference not set to an instance of an object. Code: string ConnectionString = "server=localhost\\sqlexpress;database=WindowsApp;Integrated Security=SSPI;"; SqlConnection conn = new SqlConnection(ConnectionString); conn.Open(); SqlTransaction trans = conn.BeginTransaction(IsolationLevel.Serializable); SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Test ORDER BY Id", conn); SqlCommandBuilder builder = new SqlCommandBuilder(adapter); adapter.UpdateCommand.Transaction = trans; // Create a dataset object DataSet ds = new DataSet("TestSet"); adapter.Fill(ds, "Test"); // Create a data table object and add a new row DataTable TestTable = ds.Tables["Test"]; for (int i=1;i<=50;i++) { DataRow row = TestTable.NewRow(); row["Id"] = i; TestTable .Rows.Add(row); } // Update data adapter adapter.Update(ds, "Test"); trans.Commit(); conn.Close();

    Read the article

1 2  | Next Page >