欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#实现sqlserver事务处理示例

程序员文章站 2024-02-16 00:02:04
复制代码 代码如下:private static void executesqltransaction(string connectionstring) &nbs...

复制代码 代码如下:

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);
                }
            }
        }
    }