简体   繁体   中英

Call DB2 stored procedure from C#

After reading an interesting article online: Calling DB2 stored procedures from .NET applications

I'd like to share an issue recently encountered with a derived code:

DateTime transa_date = DateTime.ParseExact(trandate, "yyyy-MM-dd", 
CultureInfo.InvariantCulture);

DB2Connection conn = new DB2Connection(MyDb2ConnectionString);
conn.Open();

try
{
    // MyDb2Connection.Open();
    // conn.Open();

    // assume a DB2Connection conn
    DB2Transaction trans = conn.BeginTransaction();
    cmd = conn.CreateCommand();

    procName = "MYTBLSCHEMA.TEST";
    procCall = "CALL MYTBLSCHEMA.TEST(@NAME, @ADDRESS_LINE, @REGNUM, @TRANSA)";

    cmd.Transaction = trans;
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = procCall; 

    // Register input-output and output parameters for the DB2Command
    cmd.Parameters.Add( new DB2Parameter("@NAME", name));       #of string type
    cmd.Parameters.Add( new DB2Parameter("@ADDRESS_LINE", adr)); #of string type
    cmd.Parameters.Add( new DB2Parameter("@REGNUM", reg));  #of string type
    cmd.Parameters.Add( new DB2Parameter("@TRANSA", transa_date)); #of date type (in DB2 table)

    // Call the stored procedure
    Console.WriteLine(" Call stored procedure named " + procName);
    cmd.ExecuteNonQuery();
}

The above code neither generates an exception at cmd.ExecuteNonQuery() nor inserts the (expected) row into the table.

Hence, a Hope to understand through this post the rationale underlying such phenomenon.

Thanks.

NB : Executing (manually)

CALL MYTBLSCHEMA.TEST('test', 'test_address_', 'test_num', 2021-01-01)

from the IDE does work (eg insert the row into the table).

DB2 version: 11.5.6.0.00000.008

I'd either remove this line:

DB2Transaction trans = conn.BeginTransaction();

Or I'd add this line at the end of the try :

trans.Commit();

As to which you'd choose; as it's a single stored procedure, unless there's some internal overriding concern within the sproc that makes sense to have a transaction to be started outside it cover it, I'd remove it. If you have, or plan to have multiple operations that must either all-succeed or all-fail, then I'd keep it/commit it..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM