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

时间:2019-02-15 13:06:07

标签: 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 & "','" & 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

1 个答案:

答案 0 :(得分:3)

您可以使用Sql Server支持的批处理命令。只需将这两个指令放在一起,然后使用ExecuteScalar。但是,在此之前,您需要尽快修复您的Sql Injection漏洞。不要串联字符串来构建sql命令,而要使用参数。

$assets-action-buttons_svg: url("<%= asset_path 'thing.svg' %>");

还要注意,保留全局连接对象是一件非常不好的事情。您不需要这样做,因为ADO.NET实现了here,这使得打开连接成为一项非常快速的操作。相反,保持周围的连接需要大量的工作才能正确地解决此问题

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

相关问题