Lijo Lijo - 2 months ago 28
C# Question

Get Byte[] from Db2 without Encoding

In

GetEmpIDInBytes_INDIRECT
method listed below, I get the following exception:


Unable to cast object of type 'System.String' to type 'System.Byte[]'.


I know that this error can be avoided if I use the following line (i.e. encoding instead of byte[] casting)

result = Encoding.ASCII.GetBytes(odbcCommand.ExecuteScalar().ToString());


But I cannot use the encoding since I don’t know what was the encoding used in the DB2 function. I need to get it back from DB2 as byte[]. How can we get it?

CODE

string sqlGetEncryptedEmpID_INDIRECT = String.Format(SQLGetEncryptedID_INDIRECT, empIDClearText);
byte[] empIDData_INDIRECT = (byte[])GetEmpIDInBytes_INDIRECT(sqlGetEncryptedEmpID_INDIRECT);



public const string SQLGetEncryptedID_INDIRECT = @"SELECT SSS.id_encrypt ('E','0000000{0}')
AS ENCRYPT_ID FROM FFGLOBAL.ONE_ROW FETCH FIRST 1 ROW ONLY WITH UR;";



private byte[] GetEmpIDInBytes_INDIRECT(string sqlQuery)
{
byte[] result = null;
string db2connectionString = ConfigurationManager.ConnectionStrings[UIConstants.DB2ConnectionString].ConnectionString;
using (OdbcConnection odbcConnection = new OdbcConnection(db2connectionString))
{
using (OdbcCommand odbcCommand = new OdbcCommand(sqlQuery, odbcConnection))
{
odbcCommand.CommandType = System.Data.CommandType.Text;
odbcConnection.Open();
result = (byte[])odbcCommand.ExecuteScalar();
//result = Encoding.ASCII.GetBytes(odbcCommand.ExecuteScalar().ToString());
}
}
return result;
}


DB2 Connection String

<add name="DB2ConnectionString_XA"
connectionString="Driver={IBM DB2 ODBC DRIVER};Database=MyDB;Hostname=DB2GWTST;
Protocol=TCPIP;Port=3700;Uid=remotxa;Pwd=xxxx;"/>

Answer

At the end, I used CAST AS CHAR(100) FOR BIT DATA in the Db2 query itself. That worked.

public const string SQLGetEncryptedIDDirect =
@"SELECT  CAST ( SSS.id_encrypt ('E','0000000{0}') AS CHAR(100) FOR BIT DATA)  
AS ENCRYPT_ID FROM FFGLOBAL.ONE_ROW FETCH     FIRST 1 ROW ONLY WITH UR;";
Comments