I am new in vb.net and MySQL database, i am to far from what i am practicing but suddenly i'm stack in getting the value of the current data of the attribute from my table which is auto increment after inserting my query. Here is my code:
Imports MySql.Data.MySqlClient
Try
Dim dbcon As New MySqlConnection
Public dbcom As New MySqlCommand
Public sql As String
Dim theID As String ' this is the variable where the auto increment ID will be stored.
dbcon.ConnectionString = "server=localhost; uid=root; pwd=; database=test;"
dbcon.Open()
sql = "insert into tableThis values('" & Name & "');" 'this will produced an auto increment value
dbcom = New MySqlCommand(sql, dbcon)
dbcom.ExecuteNonQuery()
MsgBox("Added!Your ID IS: ", & theID) ' the auto increment ID will be display
Catch ex As Exception
MsgBox("Error!")
Exit Sub
End Try
** my table is:
-------------------------------------
-- tableThis ----
-------------------------------------
-- id -- INTEGER (AUTO_INCREMENT) -
-- name -- CHAR -
-------------------------------------
Thanks! Sorry for my bad English.
The result of the last auto increment field in your connection could be obtained using
SELECT LAST_INSERT_ID()
To add this part to your current code you need
Using dbcon = new MySqlConnection("server=localhost; uid=root; pwd=; database=test;")
Using dbcom = New MySqlCommand("insert into tableThis values(@name);SELECT LAST_INSERT_ID();", dbCon)
dbcon.Open()
dbcom.Parameters.AddWithValue("@name", Name )
Dim theID = Convert.ToInt32(dbcom.ExecuteScalar())
MsgBox("Added!Your ID IS: " & theID.ToString)
End Using
End Using
I have changed other things here:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.