0

我正在使用 Access 2007 并且有一些链接到 mySQL 数据库的表。我正在使用 DAO 将记录插入到 mySQL 链接表中,并尝试使用 Select @@identity 检索插入的 PK,但该选择返回 0。

  Dim sql As String

  Dim oDB As Database
  Set oDB = CurrentDb 

  sql = "INSERT INTO Quotes ( CustomerID ) SELECT 1 AS Expr1;" 

  oDB.Execute sql 

  If oDB.RecordsAffected <> 1 Then 
    MsgBox "cannot create new quote"
    Exit Function
  End If

  Dim rsNewID As DAO.Recordset
  Set rsNewID = oDB.OpenRecordset("SELECT @@IDENTITY")  ' Create a recordset and SELECT the new Identity

  Dim intNewID As Long
  intNewID = rsNewID(0).Value ' Store the value of the new identity in variable intNewID
  'This value is 0, why?

我见过另一个这样的问题,对我来说没有得到满意的回答

4

3 回答 3

2

选择 LAST_INSERT_ID()

于 2009-04-11T08:07:22.230 回答
1

fredrik 获得了 mySQL 语句的部分功劳。需要注意的是,我使用的是 DAO,因此语句由 JET 引擎处理,它不支持此语句。这需要在 Access 中作为传递查询运行才能正常工作。在我使用 fredrik 的 select 语句进行查询后,就成功了。我从我的 DAO 代码中调用了这个 Access 直通查询,它起作用了。

于 2009-04-11T17:46:18.047 回答
0

我没用过mysql。所以,翻译一下我对mysql说的话。

CustomerID 是一个身份列(即它自己生成 ID)吗?
如果是这样,请使用返回最后生成的 ID 的函数。

@@Identity 函数是人们在 SQL Server 中使用的。我不知道mysql中的等价物。
看到这个

查看上面的代码,您不需要打开第二个记录集。rsNewID1应该可以帮助您获取最后插入的 ID 。

希望这可以帮助。

于 2009-04-11T06:03:10.327 回答