问题的实际需求是读取oracle数据库表中RAW类型列值,并根据获取的值进行一些查询、插入操作。
(1) 首先oracle中RAW类型,在.NET 中等同于byte[],获取列值。
添加引用:
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["CONNSTR"].ToString());
conn.Open();
OracleCommand cmd_ApplicationID = conn.CreateCommand();
cmd_ApplicationID.CommandType = CommandType.Text;
cmd_ApplicationID.CommandText = "select APPLICATIONID from ORA_ASPNET_APPLICATIONS where LOWEREDAPPLICATIONNAME='"+applicationName.ToLower()+"'";
OracleDataReader reader_ApplicationID = cmd_ApplicationID.ExecuteReader();
byte[] arrAPPID=new byte[16];
if(reader_ApplicationID.Read())
arrAPPID = reader_ApplicationID.GetValue(0) as byte[];
或者这样强制转换:arrAPPID = (byte[])reader_ApplicationID.GetValue(0);
(2) 下面想利用获取的列值进行查询操作,关键就是将byte []转换为string类型。因为若不转换,无法正确执行SQL语句,如下错误示例:
cmd_RoleID.CommandText = "select ROLEID from ORA_ASPNET_ROLES where LOWEREDROLENAME='" + roleName.ToLower() + "' and APPLICATIONID=" + arrAPPID ;
添加引用:using System.Text;
定义string类型变量:string APPID=string.Empty;
A、首先列出网上搜索的一些信息:
方法1:
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
byte[] inputBytes =converter.GetBytes(inputString);
string inputString = converter.GetString(inputBytes);
方法2:
string inputString = System.Convert.ToBase64String(inputBytes);
byte[] inputBytes = System.Convert.FromBase64String(inputString);
B、接着列出一些调试中出现的错误现象:
获取的byte[]类型值,如下:
语句 |
返回值 |
APPID = reader_ApplicationID.GetValue(0) as string; |
null |
APPID = System.Convert.ToString(arrAPPID); |
System.Byte[] |
APPID = System.Convert.ToBase64String(arrAPPID); |
KWB+Au5GRKGZ3XDuHSf9tA== |
System.Text.UnicodeEncoding convert = new System.Text.UnicodeEncoding(); APPID =convert.GetString(arrAPPID); |
)`~ u-26603 ?D輕?' (乱码) |
APPID = Encoding.Default.GetString(arrAPPID); |
)`~ u-26603 ?D輕?' (乱码) |
查看数据表,Oracle数据库表中存储的值为:29607E02EE4644A199DD70EE1D27FDB4
分析存储结果为十六进制字符,编写函数实现byte[]转换成十六进制string功能即可。
private string Byte2String(byte[] arrByte)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in arrByte)
{
sb.Append(b > 15 ? Convert.ToString(b, 16) : '0' + Convert.ToString(b, 16));
}
return sb.ToString();
}
调用此函数实现byte[]到string的转换,因为数据表中存储值为大写,所以利用ToUpper()方法转换下得到。
APPID = Byte2String(arrAPPID).ToUpper();
(3) 根据获取的string类型值,进行进一步的操作,例如:
OracleCommand cmd_UserID = conn.CreateCommand();
cmd_UserID.CommandType = CommandType.Text;
cmd_UserID.CommandText = "select USERID from ORA_ASPNET_USERS where LOWEREDUSERNAME='" + userName.ToLower() + "' and APPLICATIONID='" + APPID + "'";