0

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

无法将“System.String”类型的对象转换为“System.Byte[]”类型。

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

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

但我不能使用编码,因为我不知道 DB2 函数中使用的编码是什么。我需要将它作为字节 [] 从 DB2 中取回。我们怎样才能得到它?

代码

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

2 回答 2

3

考虑以下方法(使用此答案作为参考):

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

像这样使用它:

result = GetBytes(odbcCommand.ExecuteScalar().ToString());
于 2013-03-01T08:16:02.843 回答
0

最后,我在 Db2 查询本身中使用了CASTAS 。CHAR(100) FOR BIT DATA那行得通。

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;";
于 2013-03-01T10:41:01.943 回答