MS Access - C# - 检索最新插入的guid

bub*_*ubi 11 c# ms-access

有没有办法在使用C#访问时检索最新插入的guid?

我试过这个:创建了一个表,其中字段ID为autonumber,replicationID和字段名称varchar(250).

var command = myConnection.CreateCommand();
command.Connection.Open();
command.CommandText = "INSERT INTO Cars(Name) VALUES ('Pagani')";
command.ExecuteNonQuery();
command = context.Database.Connection.CreateCommand();
command.CommandText = "SELECT @@Identity";
Console.WriteLine(command.ExecuteScalar());
command.Connection.Close();
Run Code Online (Sandbox Code Playgroud)

我得到的问题是:

Console.WriteLine(command.ExecuteScalar());  
Run Code Online (Sandbox Code Playgroud)

总是显示 0

编辑

要创建表,您可以在C#OleDb连接上使用此语句(我认为从MS Access查询不起作用)

CREATE TABLE [Cars] (
 [Id] guid not null DEFAULT GenGUID(),
 [Name] text null
);
ALTER TABLE [Cars] ADD CONSTRAINT [PK_Cars_6515ede4] PRIMARY KEY ([Id])
Run Code Online (Sandbox Code Playgroud)

Hei*_*nzi 6

我知道这不是你要求的,但让我建议一个可以解决你潜在问题的替代解决方案.

在C#中创建GUID并将其传递给您的插入:

var newGuid = Guid.NewGuid();

var command = myConnection.CreateCommand();
command.Connection.Open();
command.CommandText = "INSERT INTO Cars(Id, Name) VALUES (?, 'Pagani')";
command.Parameters.AddWithValue("@Id", newGuid);   // Note: OleDb ignores the parameter name.
command.ExecuteNonQuery();

Console.WriteLine(newGuid);
Run Code Online (Sandbox Code Playgroud)

GUID是独一无二的.它是由您的应用程序还是由Access数据库驱动程序生成并不重要.

此选项在所有方面都优于之后阅读GUID:

  • 您只需要一次数据库访问.

  • 它的代码更少.

  • 这更容易.

而且你还可以省略GUID在那里你情况下,你INSERT 并不需要知道GUID -不需要改变现有的代码.


Gor*_*son 3

如果SELECT @@IDENTITY不适用于“ReplicationID”自动编号字段,则检索新记录的此类值的最可能方法是使用 Access DAO 记录集插入,如下所示:

// required COM reference:
//     Microsoft Office 14.0 Access Database Engine Object Library
var dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine();
Microsoft.Office.Interop.Access.Dao.Database db = dbe.OpenDatabase(
        @"C:\Users\Public\Database1.accdb");
Microsoft.Office.Interop.Access.Dao.Recordset rst = db.OpenRecordset(
        "SELECT [Id], [Name] FROM [Cars] WHERE FALSE", 
        Microsoft.Office.Interop.Access.Dao.RecordsetTypeEnum.dbOpenDynaset);

rst.AddNew();
// new records are immediately assigned an AutoNumber value ...
string newReplId = rst.Fields["Id"].Value;  // ... so retrieve it
// the returned string is of the form
//     {guid {1D741E80-6847-4CB2-9D96-35F460AEFB19}}
// so remove the leading and trailing decorators
newReplId = newReplId.Substring(7, newReplId.Length - 9);
// add other field values as needed
rst.Fields["Name"].Value = "Pagani";
// commit the new record
rst.Update();

db.Close();

Console.WriteLine("New record added with [Id] = {0}", newReplId);
Run Code Online (Sandbox Code Playgroud)

产生

New record added with [Id] = 1D741E80-6847-4CB2-9D96-35F460AEFB19
Run Code Online (Sandbox Code Playgroud)