在Oracle中给出这个表
create table test (bytes raw(100), chset varchar2(50))
insert into test (bytes, chset) values (hextoraw('454647'), 'iso-8859-1')
或在MSSQL中
create table test (bytes varbinary(100), chset nvarchar(50))
insert into test (bytes, chset) values (0x454647, 'iso-8859-1')
我正在寻找一个全面的例子,说明如何使用Java的文本编码支持在Java中创建Oracle的UDF。
在MSSQL中我会创建这个.Net程序集:
using System.Text;
using Microsoft.SqlServer.Server;
namespace Whatever
{
public class Common
{
[SqlFunction]
public static string Decode(byte[] Bytes, string EncodingName)
{
return Encoding.GetEncoding(EncodingName).GetString(Bytes);
}
}
}
并使用这些命令注册程序集并定义udf:
create assembly MyAssembly from '...\MyAssembly.dll'
create function decode(@bytes varbinary(max), @chset nvarchar(100))
returns nvarchar(max) as external name MyAssembly.[Whatever.Common].Decode
并在如下查询中使用它:
> select *, dbo.decode(bytes, chset) decoded from test
bytes chset decoded
0x454647 iso-8859-1 EFG
到目前为止,我已经创建了这个Java类:
import java.nio.*;
import java.nio.charset.*;
public class Common
{
public static String Decode(byte[] Bytes, String CharsetName)
{
return Charset.forName(CharsetName).decode(ByteBuffer.wrap(Bytes)).toString();
}
}
并使用这些命令创建UDF:
create directory jdir as 'C:\...';
create java class using bfile (jdir, 'Common.class');
create function jdecode(bytes raw, chset varchar2) return nvarchar2 as language java
name 'Common.Decode(java.lang.byte[], java.lang.String) return java.lang.String';
但是当我尝试使用它时,我收到了这个错误:
> select jdecode(hextoraw('454647'), 'iso-8859-1') from dual
ORA-29531: no method Decode in class Common
原来java.lang.byte []不是一个东西,把它改成只是byte []让事情有效。谢谢蒂姆!
create function jdecode(bytes raw, chset varchar2) return nvarchar2 as language java
name 'Common.Decode(byte[], java.lang.String) return java.lang.String';
这里有一个方便的表格:http://download.oracle.com/docs/cd/B19306_01/java.102/b14187/chsix.htm#BABJIJEB
答案 0 :(得分:1)
当oracle已经为此类转换提供了足够的实用程序时,您真的需要用户定义的函数(UDF)java吗?
UTL_I18N
包提供所有必需的功能。 MAP_CHARSET
功能从ISO字符集名称映射到Oracle字符集名称,然后RAW_TO_CHAR
函数将指定字符集的原始数据转换为数据库字符集中的VARCHAR2
。 / p>
Oracle 11g R2架构设置:
create table test (bytes raw(100), chset varchar2(50));
insert into test (bytes, chset) values (hextoraw('454647'), 'iso-8859-1');
查询1 :
select t.*
, UTL_I18N.RAW_TO_CHAR( bytes
, UTL_I18N.MAP_CHARSET(chset,0,1)) decoded
from test t
<强> Results 强>:
| BYTES | CHSET | DECODED |
|-------|------------|---------|
| RUZH | iso-8859-1 | EFG |