OracleCommandBuilder

When using SQL Server you can use the following code to discover stored procedure parameters.
Can the same thing be accomplished in Oracle?
Private Shared Function DiscoverSpParameterSet(ByVal connectionString As String, _
ByVal spName As String, _
ByVal includeReturnValueParameter As Boolean, _
ByVal ParamArray parameterValues() As Object) As SqlParameter()
Dim cn As New SqlConnection(connectionString)
Dim cmd As SqlCommand = New SqlCommand(spName, cn)
Dim discoveredParameters() As SqlParameter
Try
cn.Open()
cmd.CommandType = CommandType.StoredProcedure
SqlCommandBuilder.DeriveParameters(cmd)
If Not includeReturnValueParameter Then
cmd.Parameters.RemoveAt(0)
End If
discoveredParameters = New SqlParameter(cmd.Parameters.Count - 1) {}
cmd.Parameters.CopyTo(discoveredParameters, 0)
Finally
cmd.Dispose()
cn.Dispose()
End Try
Return discoveredParameters
End Function
Thanks,
Alex

There was a discussion on this earlier this year - I want to get the parameters of stored procedure from database

Similar Messages

  • ODP OracleCommandBuilder. Updating a table including DATE columns.

    Hi
    I have a problem with the OracleCommandBuilder not creating the correct update commands when I have DATE type columns in the table.
    I have created a test table (called DATETEST) with three columns:
    STRINGCOLUMN     VARCHAR2 10
    DATECOLUMN DATE
    NUMBERCOLUMN     NUMBER
    The STRINGCOLUMN is the primary key.
    Then I created a typed dataset that looks like this:
    STRINGCOLUMN     string
    DATECOLUMN string
    NUMBERCOLUMN     long
    This is the XML schema for the typed dataset:
    <?xml version="1.0" encoding="utf-8" ?>
    <xs:schema id="DateDS" targetNamespace="http://tempuri.org/DateDS.xsd" elementFormDefault="qualified" attributeFormDefault="qualified" xmlns="http://tempuri.org/DateDS.xsd" xmlns:mstns="http://tempuri.org/DateDS.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
         <xs:element name="DateDS" msdata:IsDataSet="true">
              <xs:complexType>
                   <xs:choice maxOccurs="unbounded">
                        <xs:element name="DATETEST">
                             <xs:complexType>
                                  <xs:sequence>
                                       <xs:element name="DATECOLUMN" type="xs:string" minOccurs="0" />
                                       <xs:element name="STRINGCOLUMN" type="xs:string" minOccurs="0" />
                                       <xs:element name="NUMBERCOLUMN" type="xs:long" minOccurs="0" />
                                  </xs:sequence>
                             </xs:complexType>
                        </xs:element>
                   </xs:choice>
              </xs:complexType>
         </xs:element>
    </xs:schema>
    And this is the test code:
    Dim connection As Oracle.DataAccess.Client.OracleConnection
    Dim adapter As New Oracle.DataAccess.Client.OracleDataAdapter()
    Dim dbCommand As New Oracle.DataAccess.Client.OracleCommand()
    Dim sqlstring As String
    Dim data As New DateDS() 'Typed dataset
    Const ConnectionString As String = "User Id=............."
    Try
    'Connect to database
    connection = New OracleConnection(ConnectionString)
    connection.Open()
    'Get data from table DATETEST
    dbCommand.CommandText = "SELECT STRINGCOLUMN, TO_CHAR(DATECOLUMN) AS DATECOLUMN, NUMBERCOLUMN FROM DATETEST"
    dbCommand.Connection = connection
    adapter.SelectCommand = dbCommand
    adapter.Fill(data, "DATETEST")
    'Make changes to dataset
    data.DATETEST(0).DATECOLUMN = Now()
    data.DATETEST(0).NUMBERCOLUMN = data.DATETEST(0).NUMBERCOLUMN + 1
    'Update database
    sqlstring = "SELECT * FROM DATETEST"
    adapter.SelectCommand = New OracleCommand(sqlstring, connection)
    Dim custCB As New Oracle.DataAccess.Client.OracleCommandBuilder()
    custCB.DataAdapter = adapter
    adapter.Update(data, "DATETEST")
    'Disconnect
    connection.Close()
    connection.Dispose()
    Catch exc As Exception
    MessageBox.Show(exc.Message)
    End Try
    Getting the data from the database is not a problem.
    The dataset contains the correct information.
    But updating the database is impossible.
    I get errors like:
    ORA-01861: literal does not match format string
    And if I don't specify a DATE format in the TO_CHAR statement I get this error:
    Concurrency violation: the UpdateCommand affected 0 records.
    I think I've tried everything.
    I've used the OracleGlobalization class, with the SetSessionInfo method.
    I've tried all different types of date conversions to make sure that
    the date format on the database is the same as in the dataset.
    I've tried to change the NLS parameters on the DB server and in the registry on the client.
    I've tried to change the DATECOLUMN type in the typed dataset from string to Oracle.DataAccess.Types.OracleDate
    But it still doesn't work.
    The default date format on the DB 9i server is AMERICAN,(DD-MON-RR).
    A strange thing is that when I instead of using the ODP classes use
    the System.Data.OracleClient and its OracleCommandBuilder
    the code works perfectly without any errors.
    This is the test code that works:
    Dim connection As System.Data.OracleClient.OracleConnection
    Dim adapter As New System.Data.OracleClient.OracleDataAdapter()
    Dim dbCommand As New System.Data.OracleClient.OracleCommand()
    Dim data As New DateDS()
    Dim sqlstring As String
    Const ConnectionString As String = "User Id=......."
    Try
    'Connect to database
    connection = New System.Data.OracleClient.OracleConnection(ConnectionString)
    connection.Open()
    'Get data from table DATETEST
    dbCommand.CommandText = "SELECT STRINGCOLUMN, TO_CHAR(DATECOLUMN,'YYYY-MM-DD HH24:MI:SS') AS DATECOLUMN, NUMBERCOLUMN FROM DATETEST"
    dbCommand.Connection = connection
    adapter.SelectCommand = dbCommand
    adapter.Fill(data, "DATETEST")
    'Make changes to dataset
    data.DATETEST(0).DATECOLUMN = Now()
    data.DATETEST(0).NUMBERCOLUMN = data.DATETEST(0).NUMBERCOLUMN + 1
    'Update database
    sqlstring = "SELECT * FROM DATETEST"
    adapter.SelectCommand = New System.Data.OracleClient.OracleCommand(sqlstring, connection)
    Dim custCB As New System.Data.OracleClient.OracleCommandBuilder()
    custCB.DataAdapter = adapter
    adapter.Update(data, "DATETEST")
    'Disconnect
    connection.Close()
    connection.Dispose()
    Catch exc As Exception
    MessageBox.Show(exc.Message)
    End Try
    My experience until this came up is that the ODP provider is better on everything
    than the microsoft Oracle provider so I don't want to switch unless I have to.
    Could someone that have used the ODP OracleCommandBuilder for updating a table including DATE columns with a typed dataset please give me some tips on how to make this work?
    I would be the happiest man on earth if someone had a solution :-)
    Erik

    Don't convert the dates to strings. Ever.
    The command builder uses the metadata returned from the select command to build the insert/update commands. Using to_char in the query tells ODP that that is a varchar2 column. If you omit the to_char the commandBuilder will know to bind a date parameter in that spot.
    Also in your typed dataset you should change the type from a string to a date.
    David

  • Odd behaviour of OracleCommandBuilder.DeriveParameters(OracleCommand)

    Hi Gurus,
    Kinda lost here..needs expert help.
    I have a procedure with the following signature:
    procedure my_proc(param1 in varchar2 default null)...
    Now Im using the code below:
    OracleConnection con = Connect(connectionString);
    OracleCommand cmd = new OracleCommand("my_pkg.my_proc"), con);
    cmd.CommandType = CommandType.StoredProcedure;
    OracleCommandBuilder.DeriveParameters(cmd);
    but when I check the derived parameter I notice the IsNullable property value is "false". I'm hoping this should be set by ODP.Net as "true" since it can be null. How can I enforce a constraint in my SP such that when DeriveParameters is called it will give me a IsNullable value of "true" to optional parameter(s).
    Thank you.

    Hi,
    As per the documentation here:
    http://download.oracle.com/docs/html/E15167_01/OracleParameterClass.htm#CHDGIFIG
    The OracleParameter.IsNullable property is not supported.
    Regards,
    -Naveen

  • OracleDataAdapter, OracleCommandBuilder and DBConcurrencyException.

    Hello,
    I am having some issues with the OracleDataAdapter.Update method. If I use OracleCommandBuilder to dynamically create the update command, I have no problems and it works as expected.
    But if I explicitly create the Update command and set the OracleDataAdapter.UpdateCommand property the code always throws a DBConcurrencyException.
    I am testing this with an extremely simple 2 column test table (id, name) so Im sure the sql itself is ok!
    Any advice?
    Thanks,
    Adam

    ..this method works:
         public void BuilderUpdate(DataSet set)
    string constr = "xxx";
    string cmdstr = "select id, name from test";
    OracleDataAdapter adapter = new OracleDataAdapter(cmdstr, constr);
    OracleCommandBuilder builder = new OracleCommandBuilder(adapter);
    adapter.Update(set, "Test");
    ..and this method always throws exception:
         public void CommandUpdate(DataSet set)
    string constr = "xxx";
    OracleConnection conn = new OracleConnection(constr);
    OracleCommand updateCommand = new OracleCommand("update test set name=:i_name where id =:i_id", conn);
    OracleParameter updateIdParam = new OracleParameter("i_id", OracleDbType.Int32);
    updateIdParam.SourceVersion = DataRowVersion.Current;
    OracleParameter updateNameParam = new OracleParameter("i_name", OracleDbType.Varchar2);
    updateNameParam.SourceVersion = DataRowVersion.Current;
    updateCommand.Parameters.Add(updateNameParam);
    updateCommand.Parameters.Add(updateIdParam);
    OracleDataAdapter adapter = new OracleDataAdapter();
    adapter.UpdateCommand = updateCommand;
    adapter.Update(set, "Test");
    Edited by: user10422769 on Dec 7, 2008 6:00 PM

  • OracleCommandBuilder.DeriveParameters  , Gives Connection must be Opened.

    Hi,
    I was trying to use OracleCommandBuilder.DeriveParameters method to derive paramaters of a StoredProcedure. When i run the following code it give me the following error.
    Message :- "Connection must be open for this operation"
    Stack Trace:-
    " at Oracle.DataAccess.Client.OracleCommand.ExecuteNonQuery()\r\n at Oracle.DataAccess.Client.OracleCommandBuilder.DeriveParameters(OracleCommand command)\r\n at DeriveParam.Form1.button1_Click(Object sender, EventArgs e) in d:\\dal design\\deriveparam\\form1.cs:line 100"
    Code
    string Constr= "Data Source='ORCL',User Id='scott',Password='tiger'";
                   OracleConnection Conn = new OracleConnection("Data Source=ORCL;User Id=Scott;Password=tiger");
                   OracleCommand cmd = new OracleCommand();
                   cmd.Connection=Conn;
    cmd.CommandType=System.Data.CommandType.StoredProcedure;
                   cmd.CommandText="Bank_data.B_GET_GE";
                   Conn.Open();
                   try
                        OracleCommandBuilder.DeriveParameters(cmd);
                        MessageBox.Show(cmd.Parameters.Count.ToString());
                   catch(Exception ex)
                        Conn.Close();
                        MessageBox.Show(ex.StackTrace.ToString());
    Thanks
    Sundeep

    Did you get a resolution to this?
    Using your code with ODP.NET 10.1.0.4.0 and database 10.1.0.4.0 I can not reproduce...
    - Mark

  • OracleCommandBuilder bug

    Hello,
    When you uses a OracleCommandBuilder using a DbCommandBuilder variable,
    the Parameters and CommandText for the Insert, Update and Delete commands
    are not created properly, all parameters are created as :p1, :p2, ... and all of them have a string DbType. this code can be usefull to test it:
    if (conn.State == ConnectionState.Closed)
    conn.Open();
    if (conn.State == ConnectionState.Open)
    OracleCommand selectCommand =
    new OracleCommand(selectCommandText, conn);
    DbDataAdapter da = new OracleDataAdapter();
    da.SelectCommand = selectCommand;
    DbCommandBuilder builder = new OracleCommandBuilder();
    builder.DataAdapter = da;
    da.UpdateCommand = builder.GetUpdateCommand();
    da.InsertCommand = builder.GetInsertCommand();
    da.DeleteCommand = builder.GetDeleteCommand();
    }

    IMHO, when it comes to sql statements, it's hard to make it generic. for example, when you want to do pagination, you can simply use LIMIT clause int MySQL but you have to user ROWNUM instead if you're using Oracle.
    Regards.

  • OracleCommandBuilder create InsertComman with wrong parameters

    I have a simple table:
    CREATE TABLE test_b (a NUMBER);
    Then I create command for inserting data to this:
    DbProviderFactory factory = DbProviderFactories.GetFactory("Oracle.DataAccess.Client");
    using (DbConnection connection = factory.CreateConnection())
    connection.ConnectionString = "User Id=apolyakov;Password=oracle;Data Source=OPE";
    connection.Open();
    using (DbDataAdapter adapter = factory.CreateDataAdapter())
    adapter.SelectCommand = connection.CreateCommand();
    adapter.SelectCommand.CommandText = "select * from test_b";
    using (DbCommandBuilder builder = factory.CreateCommandBuilder())
    builder.DataAdapter = adapter;
    using (var command = builder.GetInsertCommand())
    command.Parameters[0].Value = 1;
    command.ExecuteNonQuery();
    ExecuteNonQuery throw OracleTruncateException "truncated result".
    System: ODAC 11.1, .NET 2.0, WinXP, Database 10g2

    I've encountered the exact same problem. The issue seems to be with inserting into a column of type "NUMBER". Despite the fact that System.Decimal is actually a smaller type, and there's no danger of truncation, the Update command of OracleDataAdapter seems to be unable to handle this conversion.
    What's worse, even if you convert the column in the datatable and all the data to Oracle.DataAccess.Types.OracleDecimal, the result is the same. Right now OracleDataAdapter.Update seems hopelessly broken for inserting into NUMBER columns.
    .NET 4.0 Oracle 11g
    Edited by: 903858 on Dec 21, 2011 1:16 PM
    Edited by: 903858 on Dec 21, 2011 1:18 PM

  • OracleCommandBuilder (with schema prefix)

    Hi,
    I'm using a simple SELECT command :
    SELECT * FROM mySchema.myTable
    Prior, I haven't use the schema and all has worked fine (with a CommandBuilder). Now I'm using the schema prefix and the generated SLQ for an update statment looks like :
    UPDATE myTable set myAttr = ... where ...
    The mySchema. is not used by the command builder to generate the update/insert/delete statment, so the table could not be found.
    Any idea how to set the command builder that it will use the schema prefix ?
    Thanks

    This has been identified as a bug in the provider. The fix would be available in the next release.

  • OracleCommandBuilder  Update Command-- ConflictOption???

    So am looking at porting some ado.net 2.0 code to odp (managed) .
    am running into a problem though -- the odp.net docs say that the CommandBuilder.ConflictOption is not supported, even though it's there and can be set in code, but if I set it to anything, (IE OverwriteChanges) it still behaves the same (CompareAllSearchableValues).
    this is important because CompareAllSearchableValues generates a whole bunch of concurrency checking conditions for every field, and that does not work for us, where as OverwriteChanges simply updates based on the key fields, which is what we want.
    anyone know if there are plans to include support for this? or if there are working alternatives? Manually specifying the command text is not really a great option for us.   it's if not i need to either stick with the depreciated Microsoft System.Data.OracleClient or write something myself to emulate that (obviously neither is ideal).

    There are no plans for ODP.NET to support this property in the near future.

  • Unable to load DLL 'OraOps10w.dll': Access is denied.

    Below is our error message. This happens around 5 - 7AM daily, and we are struggling with identifying the root cause. It's hard for me to believe it's code related, but anything's possible. Still, what's odd is the app runs fine for a day then an IIS reset is done and everything is fixed. Is there any way this could be related to code and has anyone dealt with this error before? Could a job or some permission being run behind the scenes be using this same dll and cause it to be overwritten?
    Thanks, Bryan
    Timestamp: 3/4/2010 12:11:23 PM
    Message: HandlingInstanceID: 3d9a795c-1256-44c1-b018-f553d4023b12
    An exception of type 'System.TypeInitializationException' occurred and was caught.
    03/04/2010 07:11:23
    Type : System.TypeInitializationException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
    Message : The type initializer for 'Oracle.DataAccess.Types.OracleDecimal' threw an exception.
    Source : Oracle.DataAccess
    Help link :
    TypeName : Oracle.DataAccess.Types.OracleDecimal
    Data : System.Collections.ListDictionaryInternal
    TargetSite : Void PostBind_Int32()
    Stack Trace : at Oracle.DataAccess.Client.OracleParameter.PostBind_Int32()
    at Oracle.DataAccess.Client.OracleParameter.PostBind(OracleConnection conn, OpoSqlValCtx* pOpoSqlValCtx, Int32 arraySize)
    at Oracle.DataAccess.Client.OracleCommand.ExecuteNonQuery()
    at Oracle.DataAccess.Client.OracleCommandBuilder.DeriveParameters(OracleCommand command)
    at Microsoft.Practices.EnterpriseLibrary.Data.Odp.OdpDatabase.DeriveParameters(DbCommand discoveryCommand)
    at Microsoft.Practices.EnterpriseLibrary.Data.Database.DiscoverParameters(DbCommand command)
    Additional Info:
    MachineName : MISTERC
    TimeStamp : 3/4/2010 12:11:23 PM
    FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=2.0.0.0, Culture=neutral, PublicKeyToken=3f0a163eed2abd49
    ThreadIdentity :
    WindowsIdentity : NT AUTHORITY\NETWORK SERVICE
    Inner Exception
    Type : System.DllNotFoundException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
    Message : Unable to load DLL 'OraOps10w.dll': Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
    Source : Oracle.DataAccess
    Help link :
    TypeName :
    Data : System.Collections.ListDictionaryInternal
    TargetSite : Int32 AllocValCtxFromNoFmtStr(System.String, IntPtr ByRef)
    Stack Trace : at Oracle.DataAccess.Types.OpsDec.AllocValCtxFromNoFmtStr(String numStr, IntPtr& numCtx)
    at Oracle.DataAccess.Types.OracleDecimal.GetMaxValue()
    at Oracle.DataAccess.Types.OracleDecimal..cctor()

    Thanks a lot.
    I give permissions to ASP.NET account in directory C:\Oracle\product\10.2.0\client_4 (full control) and the application running ok.

  • Who can show me a sample ...

    sample of insert/update/delete a table using DataGrid,
    with a datetime column in this table at lease.
    and there are some NULL value in this datetime column.
    i met a lot of problem at this looking simply case.
    I am using VB.NET + ODP.NET(9.X) + Oracle 8.17.
    thank you.
    Jimyho

    My case using OracleCommandBuilder to Generate Insert/Update/Delete Command. When Save a Record,
    mark the Date to the DateTime_Column,just like follow:
    Private Sub da_RowUpdating(ByVal sender As Object, ByVal e As Oracle.DataAccess.Client.OracleRowUpdatingEventArgs) Handles da.RowUpdating
    For i As Integer = 0 To e.Command.Parameters.Count - 1
    If e.Command.Parameters(i).SourceColumn = "ENTRY_DATE" Then
    e.Command.Parameters(i).OracleDbType = OracleDbType.Date
    e.Command.Parameters(i).Value = Now
    End If
    Next
    End Sub

  • HOW TO GET AUTO GENERATED PRIMARY ID KEY BACK FROM AN INSERT STATEMENT IN .

    Just recently I ran into a problem with what seems to be a deficiency in the Oracle Database. When trying to return an auto-generated key as is done in Microsoft's SQL database, it seems Oracle for whatever reason didn't add this capability, the key couldn't be passed back to the .Net call. After tinkering with the .Net software and talking with the Oracle techs, a decent work around to the problem (presented here) comes fairly close. Two things have to be done first before this will work. A sequence has to be created on the Oracle DB. Also a trigger has to be created against the table the keys are going to be returned from.
    The class works by passing to the function 'update_datasets_return' a DataSet with as many tables as you want. The function spins through the tables and put the keys in each row inserted. It's assumed the first row will either be the primary key or some numeric value. This can be changed by modifying the: dt.Columns(0).ColumnName
    Notice the word Inserted. On Updates and Deletes the key value is ignored because it's already present. The routine just updates the database as usual.
    So in other words you could send a table to the function with rows inserted, deleted, or updated and it will take care of them all. One routine for all.
    ' ======================================================================
    ' Created by SEF and Oracle SR: 5607364.993 This is a complete Redo
    ' of the initial concept. SEF...
    ' Sample of sequence and trigger at bottom.
    ' Uses the ODP.NET data provider.
    ' update_datasets_return: Goes thru each table in the dataset and
    ' updates, deletes, or inserts as needed.
    ' If inserting, a 'sequence counter' and a 'trigger'
    ' using the 'before insert' must be present. The sequence
    ' counter is set to auto increment by 1 starting at 1.
    ' The trigger is specific to the table.
    ' Create the trigger and sequence in the database or run the samples
    ' below in PL/SQL. Be sure the logon with a user that has enough rights.
    ' Routine assumes the first column is going to hold the sequence
    ' number. Actually any column could be used. Just change the
    ' dt.Columns(0).ColumnName to whatever you want or leave as default.
    ' The da_RowUpdated sub is where the 'sequence number' gets returned
    ' on each row that is inserted into a table. Routine is ignored on
    ' deletes and updates. SEF...
    ' =======================================================================
    Imports System
    Imports System.Data
    Imports Oracle.DataAccess.Client
    Imports Oracle.DataAccess.Types
    Public Class OracleUpdate
    Private Shared m_conn As OracleConnection
    Private Shared da As New OracleDataAdapter
    Private Shared dt As DataTable
    Private Shared conn As New OracleConnection
    Private Shared dr As DataRow
    Private Shared astep As Long
    Private Shared rwIndex As Integer = 0
    Private Shared tblIndex As Integer = 0
    Public Shared Function update_datasets_return(ByVal constr As String, ByVal ds As DataSet) As DataSet ''ByRef ds As DataSet)
    Dim selectstmt As String
    m_conn = New OracleConnection(constr)
    Try
    m_conn.Open()
    Catch ex As Exception
    Throw New ArgumentException(" Error: connection lost." & ex.Message)
    End Try
    For Each dt In ds.Tables
    ''Uncomment the code only if auto numbering
    ''is NOT turned on for the table being updated. SEF...
    ''rwIndex = 0
    ''For Each dr In dt.Rows
    '' Try
    '' Select Case dr.RowState
    '' Case DataRowState.Added
    '' astep += 1
    '' ' =======================================================
    '' ' This "Try Catch" section created only if auto numbering
    '' ' is NOT turned on for the table being updated. SEF...
    '' ' It's a crude attempt at creating a unique number.
    '' ' A more serious approach would be to use a GUID.
    '' ' Use only if you decide not to have a sequence and a
    '' ' trigger for the table.
    '' ' =======================================================
    '' Try
    '' 'ds.Tables(tblIndex).Rows(rwIndex).Item(0) = astep
    '' Catch
    '' ' ignore the error corrected integer identity so don't randomize it
    '' End Try
    '' dr.Item("createdDate") = Now
    '' dr.Item("changedDate") = Now
    '' Case DataRowState.Modified
    '' dr.Item("changedDate") = Now
    '' End Select
    '' Catch ex As Exception
    '' conn.Close()
    '' conn.Dispose()
    '' Throw New ArgumentException(" Error: update_datasets " & ex.Message)
    '' End Try
    '' rwIndex += 1
    ''Next
    selectstmt = "SELECT * From " & dt.TableName & " Where " & dt.Columns(0).ColumnName & " = " & 0
    da = New OracleDataAdapter(selectstmt, m_conn)
    Dim bldr As OracleCommandBuilder = New OracleCommandBuilder(da)
    AddHandler da.RowUpdated, New Oracle.DataAccess.Client.OracleRowUpdatedEventHandler(AddressOf da_RowUpdated)
    Dim insCmd As OracleCommand = Nothing
    Try
    insCmd = CType(bldr.GetInsertCommand(), OracleCommand)
    Catch ex As Exception
    Throw New Exception("")
    End Try
    insCmd.CommandText += " returning " + dt.Columns(0).ColumnName + " into :seqno"
    insCmd.Parameters.Add(New OracleParameter("seqno", OracleDbType.Int16, _
    4, ParameterDirection.Output, False, CType(0, System.Byte), CType(0, _
    System.Byte), dt.Columns(0).ColumnName, DataRowVersion.Current, Nothing))
    da.InsertCommand = insCmd
    Try
    ' ===========================
    da.Update(ds, dt.TableName)
    ' ===========================
    Catch ex As Exception
    Throw New ArgumentException(" Error: update_datasets_return " & ex.Message)
    End Try
    Next
    m_conn.Close()
    m_conn.Dispose()
    Return ds
    End Function
    Friend Shared Sub da_RowUpdated(ByVal sender As Object, ByVal e As OracleRowUpdatedEventArgs)
    If e.StatementType = StatementType.Insert Then
    e.Row(0) = Int64.Parse(e.Command.Parameters("seqno").Value.ToString())
    End If
    End Sub
    ' ================================================================================
    ' Notes:
    ' =================== How To -- Sample section for PL/SQL ==================================
    ' myTrigger, myTable, mySequence, and myColumn are values you need to supply.
    ' Note: A trigger needs to be created for each table.
    ' A sequence needs to be created only once and referenced each time
    ' in the trigger(s). Or you could create a new sequence each time you
    ' create a trigger. Sort of a waste of effort.
    ' Explanation:
    ' myTrigger = The name you are giving this trigger.
    ' If a trigger with same name already
    ' exist, it will be overwritten.
    ' myTable = Table you want to add the sequence numbers to.
    ' mySequence = Sequence counter you created. Whatever name you called it.
    ' myColumn = The column to update with the sequence number.
    ' =================================================================================
    ' -- Run in PL/SQL or create at DB. --
    ' create or replace trigger myTrigger
    ' before insert on myTable for each row
    ' begin
    ' select mySequence.nextval into :new.myColumn from dual ;
    ' end;
    ' -- Run in PL/SQL or create at DB. --
    ' create sequence mySequence
    ' MINVALUE 1
    ' START WITH 1
    ' INCREMENT BY 1
    ' NOCACHE; can be set to CACHE but sequence may contain gaps.
    ' Explanation of CACHE from: http://www.techonthenet.com/oracle/sequences.php
    ' With respect to a sequence, the CACHE option specifies how many sequence
    ' values will be stored in memory for faster access. The downside of creating
    ' a sequence with a CACHE is that if a system failure occurs, all cached
    ' sequence values that have not be used, will be "lost". This results in
    ' a "gap" in the assigned sequence values. When the system comes back up,
    ' Oracle will CACHE new numbers from where it left off in the sequence,
    ' ignoring the so called "lost" sequence values.
    ' Note: To recover the lost sequence values, you can always execute an
    ' ALTER SEQUENCE command to reset the counter to the correct value.
    ' NOCACHE means that none of the sequence values are stored in memory.
    ' This option may sacrifice some performance, however, you should not encounter
    ' a gap in the assigned sequence values.
    End Class
    C#:
    using System;
    using System.Data;
    using Oracle.DataAccess.Client;
    using Oracle.DataAccess.Types;
    public class OracleUpdater2
    private static OracleConnection m_conn;
    private static OracleDataAdapter da = new OracleDataAdapter();
    private static OracleConnection conn = new OracleConnection();
    public static DataTable load_it(string constr, string strqry, string tblName)
    // =====================================================================
    // constr = User Id=myUser;Password=myPass";Data Source=myDataSource
    // strqry = Select * from something?
    // tblName = The table name to fill.
    // =====================================================================
    conn = new OracleConnection(constr);
    conn.Open();
    da = new OracleDataAdapter(strqry, conn);
    OracleCommandBuilder bldr = new OracleCommandBuilder(da);
    DataTable dt = new DataTable(tblName);
    da.Fill(dt);
    conn.Dispose();
    return dt;
    public static DataSet update_datasets_return(string constr, DataSet ds)
    //'ByRef ds As DataSet)
    string selectstmt = null;
    m_conn = new OracleConnection(constr);
    try
    m_conn.Open();
    catch (Exception ex)
    throw new ArgumentException(" Error: connection lost." + ex.Message);
    foreach (DataTable dt in ds.Tables)
    selectstmt = "SELECT * From " + dt.TableName + " Where " +
    dt.Columns[0].ColumnName + " = " + 0;
    da = new OracleDataAdapter(selectstmt, m_conn);
    OracleCommandBuilder bldr = new OracleCommandBuilder(da);
    da.RowUpdated += new
    Oracle.DataAccess.Client.OracleRowUpdatedEventHandler(da_RowUpdated);
    OracleCommand insCmd = null;
    try
    insCmd = (OracleCommand)(bldr.GetInsertCommand());
    catch (Exception ex)
    throw new Exception("" + ex.Message);
    insCmd.CommandText += " returning " + dt.Columns[0].ColumnName + " into
    :seqno";
    insCmd.Parameters.Add(new OracleParameter("seqno", OracleDbType.Int16, 4,
    ParameterDirection.Output, false, System.Convert.ToByte(0),
    System.Convert.ToByte(0), dt.Columns[0].ColumnName, DataRowVersion.Current,
    null));
    da.InsertCommand = insCmd;
    try
    // ===========================
    da.Update(ds, dt.TableName);
    // ===========================
    catch (Exception ex)
    throw new ArgumentException(" Error: update_datasets_return " +
    ex.Message);
    m_conn.Close();
    m_conn.Dispose();
    return ds;
    If you need a working program of how this works, let me know.

    Oh my god, it is too long! You definitely check out types, casting and especially ODP.Net (it does everything for you)... etc. They can help you to simplify your code. I do not have enough time to copy paste it to Studio and understand and solve your issue, so I got title of your message as your main question.
    In Oracle, you can create an autonumber field by using sequences object. This is really useful when you need to create a unique number to act as a primary key.
    Basically you can create a sequence simply typing;
    CREATE SEQUENCE MY_SEQUENCE;
    now you have a sequence called "MY_SEQUENCE"... Then, I advice you select a number from sequence;
    select MY_SEQUENCE.nextval from dual;
    I said I advice actually kinda must, although it called sequence, I cannot be sequential. Do not even try to predict the value. You can be sure that it is unique number so you can use it.
    Then insert you record and use that number part of your primary key. I think that's it. Have fun.

  • DataadapObject reference not set to an instance of an object in VB,NET 2003

    Huge problem, please help!
    Just installed ODT 10.1.4 and must have done something wrong. Don't know enough to be able to correct on my own.
    In VB, after install, new OracleDataAdapter, OracleConnection, OracleCommandBuilder and OracleCommand items appeared in toolbox. Tried dropping an OracleDataAdapter on the form. Immediate error in Microsoft Development Environment dialog box: Object reference not set to an instance of an object. I've tried the following:
    Updated References to include Oracle.DataAccess
    Updated Imports list to include Oracle.DataAccess and Oracle.DataAccess.Client

    Sorry, pressed wrong button. To continue:
    I've tried to drop on an existing form with an MS OracleDataAdapter already on it and a fresh form with nothing on it. The form designer will handle the other three objects (connection, commandbuilder and command) without complaint.
    Though I haven't tried to execute, adding an oracledataadapter in code seems to work -- at least no errors, and code completion does what is expected.
    What am I missing? I need that data adapter (unless someone can tell me how to get past the bug in the MS provider that produces data overflow when trying to handle Oracle type NUMBER) and am on a very very very tight deadline.
    HELP!!!!
    Thanks for anything that might work.
    Eric

  • Updating data from grid to Oracle database.

    Hi
    I am having some trouble updating data in a grid back to the Database. I have provided an example below. I am using the ODP.NET protocol.
    The query in the proc is a simple SELECT * FROM xxxx. There are no joins (outer or inner) at all. The table xxxx has a primary key. The proc is used to fill a grid. It does this correctly by returning data to a DataTable which is then used as the data source for a grid. Then, when I make a change in the grid and press the update button, the application trys to use the da.UpdateCommand = cmdBuilder.GetUpdateCommand() statement and gets the error
    "Dynamic SQL generation failed. No key information found".
    Note I have tried to get around this problem by adding a key to the DataTable ... no luck.
    I also tried da.MissingSchemaAction = MissingSchemaAction.AddWithKey ... no luck.
    I have also tried da.FillSchema(dt, SchemaType.Mapped); ... no luck.
    What am I doing wrong? ... is there a better way?
    public partial class Form1 : Form
    private OracleConnection a_Conn = null;
    private DataTable dt = null;
    private OracleDataAdapter da = null;
    private OracleCommand cmd = null;
    public Form1()
    InitializeComponent();
    private void Form1_Load(object sender, EventArgs e)
    a_Conn = new OracleConnection();
    a_Conn.ConnectionString = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    a_Conn.Open();
    dt = new DataTable();
    //SPS_TEST is a stored proc that takes no param and simply returns a dataset
    cmd = new OracleCommand("SPS_TEST", a_Conn);
    cmd.CommandType = CommandType.StoredProcedure;
    //setup ref cursor (needed for oracle)
    cmd.Parameters.Add("Cursor", OracleDbType.RefCursor, ParameterDirection.Output);
    da = new OracleDataAdapter(cmd);
    //da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
    DataColumn[] keys = new DataColumn[1];
    keys[0] = dt.Columns["Name of Column with primary key in Table I have queried"];
    dt.PrimaryKey = keys;
    da.Fill(dt);
    //grid is successfully filled at this point
    fpSpread1.DataSource = dt;
    private void btnUpdate_Click(object sender, EventArgs e)
    OracleCommandBuilder cmdBuilder = new OracleCommandBuilder(da);
    da.UpdateCommand = cmdBuilder.GetUpdateCommand();
    dt.AcceptChanges();
    da.Update(dt);
    Rob
    Edited by: user8803094 on 10-Mar-2010 19:38
    Edited by: user8803094 on 10-Mar-2010 20:56

    To the best of my knowledge, and I may be wrong here, a ref cursor does not contain any base table information. It simply contains metadata about what's in the cursor itself. The commandbuilder doesnt know what table the data came from , if it even came from an actual db table at all. As such, it's not possible for the commandbuilder to know how to generate an update statement.
    You CAN update a dataset you created from a refcursor, but you have to supply your own UpdateCommand in the case, rather than using a commandbuilder.
    If your ref cursor is simply a select from a table, it would probably be pretty easy to (at design time) get and note the updatecommand and parameters from a select * from the table, and then use that for the updatecommand of the dataset filled from a refcursor, as the metadata should match up. Probably not something you'd want to do on the fly though.
    Hope it helps,
    Corrections/comments welcome.
    Greg

  • Fail to update record in the RowUpdating event

    If I have well understood, the RowUpdating event is called before to send the row to the database.
    I want to modify the row argument of this event before to send it to oracle to add traceability info (user name of the user and the date of modification)
    No exception is raised, but the modifications I do to the row are not saved in the database.
    You will find my sample code here under.
    Thanks
    Benoit FRANC
    Atos Origin Belgium
    Sample code
    First create a table with this script:
    DROP TABLE TEST CASCADE CONSTRAINTS ;
    CREATE TABLE TEST (
    ID NUMBER (10) NOT NULL,
    DATANUMBER,
    STRING VARCHAR2 (50),
    CONSTRAINT PK_TEST
    PRIMARY KEY ( ID ) ) ;
    Manually enter a row with ID = 1; DATA=1 and STRING = "A"
    Imports System.Data
    Imports Oracle.DataAccess.Client
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim sSql As String
    Dim mConnection As OracleConnection
    mConnection = New OracleConnection("User Id=eperform;Password=eperform;Data Source=tractDev")
    mConnection.Open()
    sSql = "SELECT * FROM TEST WHERE ID = 1"
    Dim oraDA As OracleDataAdapter = New OracleDataAdapter(sSql, mConnection)
    Dim oraCB As OracleCommandBuilder = New OracleCommandBuilder(oraDA)
    Dim oraDS As DataSet = New DataSet()
    oraDA.FillSchema(oraDS, SchemaType.Source, "SourceTable")
    oraDA.Fill(oraDS, "SourceTable")
    oraDS.Tables(0).Rows(0).Item("STRING") = "Hello" & Now 'only to see the change in the bd
    Try
    AddHandler oraDA.RowUpdating, AddressOf OnRowUpdating
    oraDA.Update(oraDS, "SourceTable")
    Catch ex As Exception
    MsgBox(ex.Message)
    Debug.WriteLine(ex.Message)
    Debug.WriteLine(ex.StackTrace.ToString)
    End Try
    mConnection.Dispose()
    mConnection.Close()
    End Sub
    Private Sub OnRowUpdating(ByVal sender As Object, ByVal args As OracleRowUpdatingEventArgs)
    Try
    args.Row("DATA") = -1
    Catch ex As Exception
    Debug.WriteLine(ex.Message)
    Debug.WriteLine(ex.StackTrace.ToString)
    End Try
    End Sub

    benoit
    I have tried working with RowUpdatingEvent, RowUpdatedEvent Handler, it
    works well. I did not go through your code but I am pasting the code I had tried, updatation happens as expected. Hope that helps.
    Jagriti
    Pls:This code is not the complete class, I have pasted only the relevant methods.
    Public Function getConnection() As OracleConnection
    'Return connection reference
    Return conn
    End Function
    'This method updates the database using dataAdapter
    Public Function UpdateRecords()
    Try
    sbox.AppendText("Updating the database" + Environment.NewLine)
    sbox.Update()
    'Update the database with the help of dataAdapter update method
    dataAdapter.Update(dset, "COUNTRYTAB")
    sbox.Update()
    Catch ex As Exception
    sbox.AppendText("Error while Updating the database" + Environment.NewLine)
    sbox.AppendText(ex.ToString() + Environment.NewLine)
    sbox.Update()
    End Try
    End Function
    'RowUpdating EventHandler
    Private Sub OnRowUpdating(ByVal sender As Object, ByVal e As OracleRowUpdatingEventArgs)
    sbox.AppendText("** OnRowUpdating() Called **" + Environment.NewLine)
    sbox.Update()
    End Sub
    'RowUpdated EventHandler
    Private Sub OnRowUpdated(ByVal sender As Object, ByVal e As OracleRowUpdatedEventArgs)
    sbox.AppendText("** OnRowUpdated() Called **" + Environment.NewLine)
    sbox.Update()
    End Sub
    'This method adds a RowUpdating event handler if it 'is not added already.
    Public Function AddUpdatingHandler()
    If updatingCount = 0 Then
    'Add the eventHandler
    AddHandler dataAdapter.RowUpdating, AddressOf OnRowUpdating
    updatingCount = 1
    End If
    End Function
    'This method adds a RowUpdated event handler if it is not added already.
    Public Function AddUpdatedHandler()
    If updatedCount = 0 Then
    'Add the eventHandler
    AddHandler dataAdapter.RowUpdated, AddressOf OnRowUpdated
    updatedCount = 1
    End If
    End Function

Maybe you are looking for