从Db2获取字节[],无需编码 [英] Get Byte[] from Db2 without Encoding

查看:295
本文介绍了从Db2获取字节[],无需编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面列出的 GetEmpIDInBytes_INDIRECT 方法中,我收到以下异常:

In GetEmpIDInBytes_INDIRECT method listed below, I get the following exception:


无法将类型为'System.String'的对象类型'System.Byte []'。

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

我知道这个错误可以如果我使用以下行(即编码而不是byte [] cast)避免使用)

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());

但是我不能使用编码,因为我不知道在DB2函数中使用的编码是什么。我需要从DB2作为byte []获取它。我们如何得到它?

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?

代码

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连接字符串

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


推荐答案

最后,我使用 AS CHAR(100)FOR BIT DATA 这个工作。

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;";

这篇关于从Db2获取字节[],无需编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆