如何在将数据插入mysql db时获取ID?

时间:2017-05-03 07:21:18

标签: mysql vb.net

下面是我的表结构,id是主键,cat_code是唯一的。

--------------------------------------
 id   cat_code  cat_name  created_by
--------------------------------------

如何在将数据插入数据库后返回id?如果记录不重复,cmd.LastInsertedId可以返回id,但是当记录重复时cmd.LastInsertedId总是返回0,如果记录重复,如何获取实际id?

                Dim query As String = "INSERT INTO main_item_cat(cat_code,cat_name,created_by)" &
                                      "VALUES (@cat_code,@cat_name,@created_by)" &
                                      "ON DUPLICATE KEY UPDATE 
                                       cat_code=@cat_code,
                                       cat_name=@cat_name,
                                       created_by=@created_by"

                Using cmd = New MySqlCommand(query, conn)
                    For Each drow As DataRow In dt_main_item_cat.Rows
                        cmd.Parameters.AddWithValue("@cat_code", drow(0).Trim())
                        cmd.Parameters.AddWithValue("@cat_name", drow(1).Trim())
                        cmd.Parameters.AddWithValue("@created_by", g_currUser)
                        cmd.ExecuteNonQuery()
                        cmd.Parameters.Clear()

                        dt_cat_dtl.Rows.Add(cmd.LastInsertedId, drow(0), drow(1))
                    Next
                End Using

0 个答案:

没有答案