我有一个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
它正在工作,除了我试图在插入此数据后从数据库获取ID号。我该怎么办?
答案 0 :(得分:1)
您应该将查询更改为
.CommandText = "INSERT INTO software (`date`, `ip`, `activate`, `cdkey`)
values (@date,@ip,@activate,@cdkey);
SELECT LAST_INSERT_ID();"
然后调用ExecuteScalar而不是ExecuteNonQuery并从LAST_INSERT_ID()中获取值
Dim newID As Integer = sqlCommand.ExecuteScalar()