14.7.txt

来自「《Microsoft Visual C# .NET 2003开发技巧大全》源代码」· 文本 代码 · 共 49 行

TXT
49
字号
Listing 14.7 Supporting Transactions
using System;
using System.Data;
using System.Data.SqlClient;
namespace _21_Transaction
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
SqlConnection connection = new SqlConnection(“Integrated
Security=SSPI;Data
[ic:ccc]Source=VCSMARKHSCH6;Initial Catalog=Northwind;”);
connection.Open();
SqlCommand insertCommand = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction
transaction = connection.BeginTransaction();
// assign connection and transaction to command
insertCommand.Connection = connection;
insertCommand.Transaction = transaction;
try
{
// this command will succeed
insertCommand.CommandText =
“Insert into Products (ProductName ) VALUES (‘New Product’)”;
insertCommand.ExecuteNonQuery();
// this command intentionally fails
// since ProductName cannot be null
insertCommand.CommandText =
“Insert into Products (ProductName) VALUES (null)”;
insertCommand.ExecuteNonQuery();
transaction.Commit();
Console.WriteLine(“Database Updated Successfully”);
}
catch(Exception e)
{
transaction.Rollback();
Console.WriteLine( e.Message );
}
finally
{
connection.Close();
}
}
}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?