使用VB.NET和Oracle中的参数化查询从插入的记录中返回ID

时间:2015-07-24 12:50:56

标签: vb.net oracle

我试图在没有运气的情况下检索插入记录的id。我已经能够成功运行查询,并且插入了记录,但我无法获取插入的记录ID。

这是我的功能:

Public Function InsertFile(ByVal file_name As String, _
                           ByVal project_id As Integer, _
                           ByVal folder_id As Integer, _
                           ByVal public_access As Integer, _
                           ByVal isProtected As Integer, _
                           ByVal uploaded_by As Integer, _
                           ByVal file_description As String) As Integer
        Dim connection As New OracleClient.OracleConnection(sConnectionstring)
        Dim command As New OracleClient.OracleCommand()
        Dim file_id As Integer

        Try
            connection.Open()
            command = connection.CreateCommand
            command.CommandType = CommandType.Text
            command.CommandText = "insert into data_file (file_name, project_id, folder_id, public_access, protected, uploaded_by, file_description) "
            command.CommandText += " values (:p1, :p2, :p3, :p4, :p5, :p6, :p7) returning file_id into :p8"
            command.Parameters.AddWithValue("p1", file_name)
            command.Parameters.AddWithValue("p2", project_id)
            command.Parameters.AddWithValue("p3", folder_id)
            command.Parameters.AddWithValue("p4", public_access)
            command.Parameters.AddWithValue("p5", isProtected)
            command.Parameters.AddWithValue("p6", uploaded_by)
            command.Parameters.AddWithValue("p7", file_description)
            command.Parameters.Add("p8")
            command.ExecuteNonQuery()
            file_id = command.Parameters.Item("p8").Value.ToString()
        Catch ex As Exception
            ProjectData.SetProjectError(ex)
            Dim builder As StringBuilder = _strOracleErrorMessage
            builder.Remove(0, builder.Length)
            builder.Append("LAST ORACLE ERROR GENREATED: ")
            builder.Append(Now.ToString)
            builder.Append(ChrW(13) & ChrW(10))
            builder.Append("MESSAGE: ")
            builder.Append(ex.Message)
            ProjectData.ClearProjectError()
            Return file_id = -9999
        Finally
            connection.Close()
        End Try

        connection.Dispose()
        command.Dispose()
        GC.Collect()

        Return file_id

End Function

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

在挖掘之后,我意识到我没有将p8参数设置为输出

我添加了以下行:

command.Parameters.item(command.Parameters.Count -1).Direction = ParameterDirection.Output

之后

command.Parameter.Add("p8")

我工作了。