首页 > 解决方案 > 如何从 MySQL 数据库中获取最后一个插入值并更新 Access 中的字段?

问题描述

我有一个涉及人类遗骸的复杂数据库,因此输入数据的 Access 表单也相当复杂。我有几个子表单(Skeleton_index、Element_index 和其他一些)。我提到的两个子表单在一个未绑定的主表单上将数据发送到它们各自的字段(element_link、skeleton_link),其他表单从中使用数据。对于 Skeleton_index,用户必须输入个人姓名,它会立即显示在 Skeleton_index 字段中。我遇到的问题是我不希望用户必须输入 Element_index 的主键数据,因为它应该是 auto_increment。这是一个问题,因为 Element_id 中的自动递增值不会立即显示在 element_link 字段中。为了让它显示,用户必须创建一个新元素,然后返回到他们正在编辑的那个。

我想要做的是在 Element_id 文本框获得焦点时将其更新为新的 auto_increment 主键。VBA 代码应从 MySQL (InnoDB) Element_index 表中获取最后一个主键,向其添加一个,然后更新 Element_index 表单中 Element_id 字段中的值。

这是我的尝试,它只是失败了。

Private Sub Element_id_GotFocus()
    SQL = "SELECT LAST_INSERT_ID();"
    lastID = DoCmd.RunSQL(SQL)
    newID = Int(lastID) + 1
    Element_id.Value = newID
End Sub

编辑:

数据库最初只有一个用户,但将来可能会有更多。

解决方案:我添加了一个带有两个宏的按钮:一个用于保存插入的记录,另一个用于刷新表单。无需复杂的 VBA。

标签: mysqlvbaformsms-accesslast-insert-id

解决方案


你的尝试在很多方面都是错误的。主要的有:

  1. 您不能用于DoCmd.RunSQL运行选择查询。它只运行操作查询。
  2. 您需要使用直通查询来运行包含 MySQL 特定函数的查询。
  3. LAST_INSERTED_ID()除非您通过用于将行插入您感兴趣的表的相同连接执行它,否则您不能使用它。

您最好使用 QueryDef 执行直通查询,并使用 INFORMATION_SCHEMA.TABLES 表检索下一个自动编号:

'Create a new temporary query, uses `With` instead of storing it in a variable
With CurrentDb.CreateQueryDef("")
    'Make it a pass-through query that connects to MySQL
    .Connect = "ODBC;<enter connection string here>"
    'Set the SQL for the query: queries table definition, gets auto_increment seed
    .SQL = "SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ""<table name here>"" AND TABLE_SCHEMA = ""<database name here>"""
    'The query should return records (not an action query)
    .ReturnsRecords = True
    'Execute the query, get the results into a snapshot-type recordset
    'And set your field equal to the first column of the first row of the recordset
    Element_id.Value = .OpenRecordset(dbOpenSnapshot).Fields(0).Value
End With

推荐阅读