简体   繁体   English

使用TableAdapter和MySQL的Last_Insert_Id问题

[英]Last_Insert_Id issues using TableAdapter with MySQL

I am having an issue using Last_Insert_Id in a VB.NET TableAdapter Insert query wired to a MySQL database. 我在VB.NET TableAdapter插入连接到MySQL数据库的查询中使用Last_Insert_Id时遇到问题。 I've read through numerous posts on this site and others regarding Last_Insert_ID and Scope_Identity, etc. None of which have worked in my case. 我已经阅读了该站点上的许多帖子,以及有关Last_Insert_ID和Scope_Identity等的其他帖子。在我的情况下,这些帖子均无效。

A little background, I have two tables, one holds login information (Auto-generated ID, username, password). 有点背景,我有两个表,一个表保存登录信息(自动生成的ID,用户名,密码)。 Another table has a foreign key relationship on the ID values and contains ID, first name, last name, city, state. 另一个表在ID值上具有外键关系,并且包含ID,名字,姓氏,城市,州。

In my TableAdapter I have an Insert query that inserts values into the first table and is supposed to return the ID value so that an Insert can be done on table 2. 在我的TableAdapter中,我有一个Insert查询,该查询将值插入第一个表中,并应返回ID值,以便可以在表2上进行插入。

Here is my Query: 这是我的查询:

INSERT INTO user_logins (user_login, user_pass)  
VALUES (@p1, @p2)

I wanted to add Last_Insert_Id to make the query 我想添加Last_Insert_Id进行查询

INSERT INTO user_logins (user_login, user_pass)
VALUES (@p1, @p2)
SELECT LAST_INSERT_ID();

However that will only return a value of 1, regardless of what the ID is. 但是,无论ID是什么,它只会返回值1。 If I open the Query Builder I get a message that states "Unable to parse query text". 如果打开查询生成器,则会收到一条消息,指出“无法解析查询文本”。 I tried changing the ExecuteMode to Scalar, but that didn't help either. 我尝试将ExecuteMode更改为Scalar,但这也无济于事。

The Insert part is working perfectly, if I could only obtain the ID value back after insert. 如果我只能在插入后获得ID值,则插入部分可以正常工作。

Does anyone know anything I might try, or alternatively, some better way to achieve this? 有谁知道我可能尝试的任何方法,或者有其他更好的方法来实现这一目标?

Thanks! 谢谢!

You don't even need to use SELECT LAST_INSERT_ID(); 您甚至不需要使用SELECT LAST_INSERT_ID();。 just INSERT INTO user_logins (user_login, user_pass) VALUES (@p1, @p2) is OK To retrieve last insert Id you can use two ways 只需INSERT INTO user_logins(user_login,user_pass)VALUES(@ p1,@ p2)就可以了。要检索最后一个插入ID,可以使用两种方法

Dim t As Integer
cmd.ExecuteNonQuery()
t = (Int32) cmd.LastInsertedId

OR 要么

t = Convert.ToInt32(cmd.ExecuteScalar())

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

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