📄 14.7.txt
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -