无法获取插入记录的ID

时间:2014-07-29 04:48:49

标签: mysql vb.net

我正在使用Visual Studio 2010将记录插入MySql中的表中。表格设置如下:

  • id - 主键 - 自动增量
  • first - varchar(45)
  • last - varchar(45)

当我插入新记录时,我想知道该记录的id值。

我将此查询添加到名为“insertQuery”的tableAdapter中。使用select @@identity;获取ID。

INSERT INTO `results` (`first`, `last`) VALUES (@p1, @p2); select @@identity;

这是我的代码:

Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.ResultsTableAdapter.Fill(Me.myDataSet.results)

        test()

        Me.Close()
    End Sub

    Private Sub test()
        Dim newID As Integer

        newID = Me.ResultsTableAdapter.InsertQuery("John", "Smith")

        MsgBox(newID.ToString)
    End Sub
End Class

记录正确插入到数据库中,但问题是我的newID变量的值始终为1.

任何想法为什么?

2 个答案:

答案 0 :(得分:1)

使用mysql_insert_id()函数,如图here

所示
if ((result = mysql_store_result(&mysql)) == 0 &&
mysql_field_count(&mysql) == 0 &&
mysql_insert_id(&mysql) != 0)

{
  used_id = mysql_insert_id(&mysql);
}

答案 1 :(得分:0)

好的,我终于能够让它发挥作用了。我需要做的就是将查询的ExecuteMode属性从NonQuery更改为Scalar。

我在本周早些时候有这个工作,今天某个时候我以某种方式改变了这个属性。我快要疯了哈哈。

相关问题