【发布时间】:2009-06-02 15:47:56
【问题描述】:
我正在尝试获取已通过 ADO.NET 事务成功输入数据库的数据。
一旦您调用了 trans.Commit() ,似乎没有办法取回已提交的数据,因为在事务期间创建的所有身份列都是“虚拟的”,因为它是离线的直到提交的数据集
非常感谢
[编辑]
啊,问题是,我无法重新选择,因为除了作为交易的一部分插入的数据的身份之外,我没有任何独特的选择。
我无法获取最后输入的项目,因为这是一个多用户系统
一本书的代码示例,不是有问题的代码,但足以说明我需要什么:
using System.Data;
using System.Data.SqlClient;
namespace DataAdapterTransaction
{
class Program
{
private static string sqlConnectString = "Data Source=(local);" +
"Integrated security=SSPI;Initial Catalog=AdoDotNet35Cookbook;";
private static string sqlSelect = "SELECT * FROM DataAdapterTransaction";
static void Main(string[] args)
{
object[,] o1 = {{ "1", "field 1.1", "field 2.1" },
{ "2", "field 1.2", "field 2.2" }};
InsertRecords(o1);
object[,] o2 = {{ "3", "field 1.3", "field 2.3" },
{ null, "field 1.4", "field 2.4" }};
InsertRecords(o2);
// Retrieve and output the contents of the table
SqlDataAdapter daRead = new SqlDataAdapter(sqlSelect, sqlConnectString);
DataTable dtRead = new DataTable( );
daRead.Fill(dtRead);
Console.WriteLine("---TABLE DataAdapterTransaction---");
foreach (DataRow row in dtRead.Rows)
Console.WriteLine("Id = {0}\tField1 = {1}\tField2 = {2}",
row["Id"], row["Field1"], row["Field2"]);
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
static void InsertRecords(object[,] o)
{
DataTable dt = new DataTable( );
SqlTransaction tran;
SqlConnection connection = new SqlConnection(sqlConnectString);
// Create a DataAdapter
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connection);
// Stop updating when an error is encountered for roll back.
da.ContinueUpdateOnError = false;
// Create CommandBuilder and generate updating logic.
SqlCommandBuilder cb = new SqlCommandBuilder(da);
// Create and fill a DataTable with schema and data
da.Fill(dt);
// Open the connection
connection.Open( );
// Begin a new transaction and assign it to the DataAdapter
tran = connection.BeginTransaction( );
da.SelectCommand.Transaction = tran;
// Add two rows that will succeed update
for (int i = 0; i <= o.GetUpperBound(0); i++)
{
dt.Rows.Add(new object[] { o[i, 0], o[i, 1], o[i, 2] });
Console.WriteLine(
"=> Row with [Id = {0}] added to DataTable.", o[i, 0]);
}
Console.WriteLine("=> Updating data source using DataAdapter.");
try
{
da.Update(dt);
tran.Commit( );
Console.WriteLine("\nTRANSACTION COMMIT.\n");
}
catch (Exception ex)
{
tran.Rollback( );
Console.WriteLine("\nTRANSACTION ROLLBACK.\n{0}\n", ex.Message);
}
finally
{
connection.Close( );
}
}
}
}
好的,所以我要在事务提交之后,我想获取最后插入的行的(范围)身份。
作为事务的一部分,我的应用程序成功更新了三个数据适配器,但是我很难查看最终提交的数据。我可以选择表格并在其中查看,但这对于生产代码来说确实不够好。
SC
【问题讨论】:
标签: sql sql-server-2005 ado.net transactions