Vb.net 获取数据库中最后插入的主键记录

Vb.net 获取数据库中最后插入的主键记录,vb.net,Vb.net,请帮助获取最后一条插入记录的主键,该记录在数据库中为我提供了重复的行,并返回0 Try If Conn.State = ConnectionState.Open Then Conn.Close() 'insert the new customer data Conn.Open() cmd = New SqlCommand("insert into Quote values ('" & dateOFCreat & "'

请帮助获取最后一条插入记录的主键,该记录在数据库中为我提供了重复的行,并返回0

Try
        If Conn.State = ConnectionState.Open Then Conn.Close()
        'insert the new customer data
        Conn.Open()
        cmd = New SqlCommand("insert into Quote values ('" & dateOFCreat & "','" & Emp & "','" & Customer_no & "' )", Conn)

        Dim a As Integer = cmd.ExecuteNonQuery()
        Dim results As Integer
        Dim cmd_results As SqlCommand
        'Get the last created Quote in the Database
        cmd_results = New SqlCommand("Select @@Identity from Quote", Conn)
        results = cmd.ExecuteScalar

        TxtLastQuoteID.Text = results

        If a = 0 Then
            MsgBox("Error")
        End If
        Conn.Close()

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

您可以使用Sql Server支持的批处理命令。把这两条指令放在一起,然后使用ExecuteScalar。然而,在此之前,您需要尽快修复Sql注入漏洞。不要连接字符串以生成sql命令,而是使用参数

Try
    Using con as SqlConnection = new SqlConnection(....constringhere...)
        Conn.Open()
        Dim sqlText = "insert into Quote values (@dat,@emp,@cusno); SELECT SCOPE_IDENTITY()"
        cmd = New SqlCommand(sqlText,Conn)
        cmd.Parameters.Add("@dat", SqlDbType.NVarChar).Value = dateOFCreat 
        cmd.Parameters.Add("@end", SqlDbType.NVarChar).Value = emp 
        cmd.Parameters.Add("@cusno", SqlDbType.NVarChar).Value = Customer_no
        Dim lastID As Integer = cmd.ExecuteScalar()
        TxtLastQuoteID.Text = lastID.ToString()
        Conn.Close()
    End Using
Catch ex As Exception
    MsgBox(ex.Message)
End Try
还要注意,保留全局连接对象是一件非常糟糕的事情。您不需要这样做,因为ADO.NET实现了使打开连接成为一个非常快速的操作。相反,保持一个连接需要付出大量的努力才能正确地处理它


最后,您可以更好地了解SCOPE_IDENTITY和@IDENTITY之间的区别,以及为什么通常使用第一个更好。

ExecuteScalar不是只返回一个0,表示查询已成功执行吗?不需要输出参数吗?ExecuteScalar将返回上次执行的SELECT语句中第一行第一列的值。在这种情况下,它是SELECT SCOPE_标识。您不需要为此设置输出参数