简体   繁体   English

如何在插入 MYSQL 之前获取下一个自动增量 ID

[英]How to Get Next Auto Increment ID Before Inserting MYSQL

I am working on a C# standalone data entry application.我正在开发一个 C# 独立数据输入应用程序。 This system is proposed to use by a centralized database(MYSQL 8.0) with many computers.该系统建议由具有多台计算机的集中式数据库(MYSQL 8.0)使用。 Data will enter using the wizard.数据将使用向导输入。 Clicking next ->next and insert data only at the end of the wizard Currently am getting the next ID by Client-side(c#)单击下一步 - > 下一步并仅在向导末尾插入数据目前正在通过客户端(c#)获取下一个 ID

SELECT MAX(id) + 1 AS ID
FROM TABLE_NAME

This method is ok for single-user applications.此方法适用于单用户应用程序。 but when the database centralized and used by many computers it will crash IDs generated by this method.但是当数据库集中并被多台计算机使用时,这种方法生成的ID会崩溃。

Example - there are 3 (A, B) computers with installed the data entry system connected to a centralized database.示例 - 有 3 台 (A, B) 计算机安装了连接到中央数据库的数据输入系统。 assume the last ID in TABLE is 5. Computer 'A' going to add data.假设表中的最后一个 ID 是 5。计算机“A”将添加数据。 Computer A will get the next ID as 6. Also, Computer 'B' starting to enter data at the same time.计算机 A 将获得下一个 ID 为 6。此外,计算机“B”同时开始输入数据。 COmputer 'B' also get the next ID as 6.Then IDs will crash.计算机“B”也将下一个 ID 设为 6。然后 ID 将崩溃。

Can anyone suggest a solution to get the next id without the crash from the server-side?任何人都可以提出一个解决方案来获取下一个 id 而不会从服务器端崩溃吗? Please Provide an example.请举例说明。

The problem is that if you do try to get next ID (especially in a multi-client environment) it is not guaranteed to be the value by the time you perform the INSERT since one client could request and then another client request, both receiving the same response, and then one of the client performs the INSERT and ID matches what was returned while the other client's ID will not.问题是,如果您确实尝试获取下一个 ID(尤其是在多客户端环境中),则不能保证在您执行 INSERT 时是该值,因为一个客户端可以请求然后另一个客户端请求,两者都接收相同的响应,然后其中一个客户端执行 INSERT 并且 ID 匹配返回的内容,而另一个客户端的 ID 则不会。

Thee 2 most basic approaches that you may want to evaluate in your given scenario are:您可能希望在给定场景中评估的 2 种最基本方法是:

  • Return the ID to the client after the INSERT is performed执行 INSERT 后将 ID 返回给客户端
  • Change the ID from an auto-incremented ID to a GUID which can be generated by the client and passed into the database during the INSERT;将 ID 从自动递增的 ID 更改为可由客户端生成并在 INSERT 期间传递到数据库的 GUID; this is a common solution for distributed applications since the values are exceptionally unlikely not to be unique.这是分布式应用程序的常见解决方案,因为这些值极不可能不是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM