簡體   English   中英

如何在vb.net 2010中的Insert語句后獲取自動增量值

[英]How to Get the Auto-Increment Values after Insert Statement i n vb.net 2010

我是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                     -
-------------------------------------

謝謝! 對不起,我的英語不好。

您連接中最后一個自動增量字段的結果可以使用

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

我在這里更改了其他內容:

  • 首先,您應該始終使用參數化查詢而不是字符串連接(有關Sql Injection的知識,以了解原因)
  • 其次,我已在可拋棄對象周圍使用了using語句來正確處理連接和命令。
  • 第三,我已將兩個命令一起傳遞,並用分號將它們分開,並使用ExecuteScalar檢索了所得的自動增量。 還要注意,autoincrement列的類型為integer而不是字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM