none
ExecuteNonQuery中包含commit操作吗?就是说在执行ExecuteNonQuery的时候有没有自动执行commit RRS feed

答案

全部回复

  • 如果没有放在事务中,默认是自动commit的。(对sql server来说)

    family as water

    2012年12月14日 1:45
  • 就是说在执行ExecuteNonQuery的时候有没有自动执行commit?

    如果你需要手动的话,那么应该使用SqlConnection的BeginTranscation方法,配合SqlTranscation的Commit或者RollBack进行手动处理,或者直接写一个存储过程(包含事务处理),然后用SqlCommand调用即可。

    private static void ExecuteSqlTransaction(string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
    
            SqlCommand command = connection.CreateCommand();
            SqlTransaction transaction;
    
            // Start a local transaction.
            transaction = connection.BeginTransaction("SampleTransaction");
    
            // Must assign both transaction object and connection 
            // to Command object for a pending local transaction
            command.Connection = connection;
            command.Transaction = transaction;
    
            try
            {
                command.CommandText =
                    "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
                command.ExecuteNonQuery();
                command.CommandText =
                    "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
                command.ExecuteNonQuery();
    
                // Attempt to commit the transaction.
                transaction.Commit();
                Console.WriteLine("Both records are written to database.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
                Console.WriteLine("  Message: {0}", ex.Message);
    
                // Attempt to roll back the transaction. 
                try
                {
                    transaction.Rollback();
                }
                catch (Exception ex2)
                {
                    // This catch block will handle any errors that may have occurred 
                    // on the server that would cause the rollback to fail, such as 
                    // a closed connection.
                    Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                    Console.WriteLine("  Message: {0}", ex2.Message);
                }
            }
        }
    }

    我的博客园
    慈善点击,点击此处
    和谐拯救危机,全集下载,净化人心

    2012年12月14日 5:14
    版主