在mysql中插入数据后如何获取插入id

lfapxunr  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(470)

这个问题在这里已经有答案了

从mysql insert query获取新的记录主键id(12个答案)
返回vb.net mysql插入行的最后一个id(标识)(3个答案)
使用c#(5个答案)获取插入行的id
两年前关门了。
我有一个mysql数据表,其中包含以下详细信息:

ID (int format) [AUTO_INCREMENT] 
date (varchar) 
ip (varchar)
activate(varchar) 
cdkey(varchar)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using SQLConnection As New MySqlConnection(ConnectionString)
            Using sqlCommand As New MySqlCommand()
                With sqlCommand
                    .CommandText = "INSERT INTO software (`date`, `ip`, `activate`, `cdkey`) values (@date,@ip,@activate,@cdkey)"
                    .Connection = SQLConnection
                    .CommandType = CommandType.Text
                    .Parameters.AddWithValue("@ip", Label1.Text)
                    .Parameters.AddWithValue("@date", TextBox2.Text)
                    .Parameters.AddWithValue("@activate", "Yes")
                    .Parameters.AddWithValue("@cdkey", textbox4.Text)

                End With
                Try
                    SQLConnection.Open()
                    sqlCommand.ExecuteNonQuery()
                    iReturn = True
                    MsgBox("Display Last Insert ID here")

                Catch ex As MySqlException
                    MsgBox(ex.Message.ToString)
                    iReturn = False
                Catch ex As Exception
                Finally
                    SQLConnection.Close()
                End Try
            End Using
        End Using
        Return
    End Sub

它的工作,除了我正试图从数据库中获得身份证号码后,这个数据被插入。我该怎么做?

8e2ybdfx

8e2ybdfx1#

您应该将查询改为

.CommandText = "INSERT INTO software (`date`, `ip`, `activate`, `cdkey`) 
                  values (@date,@ip,@activate,@cdkey);
                  SELECT LAST_INSERT_ID();"

然后调用executescalar而不是executenonquery,并从上一个\u insert \u id()中获取值

Dim newID As Integer = sqlCommand.ExecuteScalar()

相关问题