【问题标题】:Get Byte[] from Db2 without Encoding从 Db2 中获取 Byte[] 而不进行编码
【发布时间】:2013-03-01 08:01:34
【问题描述】:

在下面列出的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;"/>

【问题讨论】:

  • odbcCommand.ExecuteScalar().GetType() 返回的是什么?什么数据类型返回SSS.id_encrypt
  • 什么是列类型?
  • 似乎是 sql 作业。使用convert 函数。例如:... convert(varbinary(2024), SSS.id_encrypt ('E','0000000{0}'), 0) ...。顺便说一句,尚未测试。
  • @AlexFilipovici 它正在返回System.String

标签: c# db2


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    最后,我在 Db2 查询本身中使用了CAST AS 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;";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 2019-07-22
      • 2011-09-19
      • 1970-01-01
      相关资源
      最近更新 更多