我是vb.net和MySQL数据库的新手,我离我正在练习的东西很远但突然我在堆栈中从我的表中获取属性的当前数据的值,这是插入我的后自动增量查询。这是我的代码:
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
** 我的表是:
-------------------------------------
-- tableThis ----
-------------------------------------
-- id -- INTEGER (AUTO_INCREMENT) -
-- name -- CHAR -
-------------------------------------
谢谢!对不起,我的英语不好。
答案 0 :(得分:0)
可以使用
获取连接中最后一个自动增量字段的结果SELECT LAST_INSERT_ID()
要将此部分添加到当前代码中,您需要
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
我在这里更改了其他内容: