从Db2中获取Byte[],不带编码
本文关键字:编码 Db2 获取 Byte | 更新日期: 2023-09-27 18:01:36
在下面列出的GetEmpIDInBytes_INDIRECT
方法中,我得到以下异常:
无法强制转换"System"类型的对象。字符串'到类型'System.Byte[]'.
我知道这个错误可以避免,如果我使用以下行(即编码而不是byte[]强制转换)
result = Encoding.ASCII.GetBytes(odbcCommand.ExecuteScalar().ToString());
但是我不能使用编码,因为我不知道DB2函数中使用的编码是什么。我需要将它作为byte[]从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;"/>
考虑以下方法(使用此答案作为参考):
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());
最后,我在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;";