gor*_*rdy 5 java sql oracle user-defined-functions java-stored-procedures
鉴于Oracle中的这个表
create table test (bytes raw(100), chset varchar2(50))
insert into test (bytes, chset) values (hextoraw('454647'), 'iso-8859-1')
Run Code Online (Sandbox Code Playgroud)
或者在MSSQL中
create table test (bytes varbinary(100), chset nvarchar(50))
insert into test (bytes, chset) values (0x454647, 'iso-8859-1')
Run Code Online (Sandbox Code Playgroud)
我正在寻找一个全面的例子,说明如何使用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
并使用这些命令注册程序集并定义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
Run Code Online (Sandbox Code Playgroud)
并在这样的查询中使用它:
> select *, dbo.decode(bytes, chset) decoded from test
bytes chset decoded
0x454647 iso-8859-1 EFG
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经创建了这个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();
}
}
Run Code Online (Sandbox Code Playgroud)
并使用这些命令来创建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';
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用它时,我收到此错误:
> select jdecode(hextoraw('454647'), 'iso-8859-1') from dual
ORA-29531: no method Decode in class Common
Run Code Online (Sandbox Code Playgroud)
原来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';
Run Code Online (Sandbox Code Playgroud)
这里有一个方便的表:http://download.oracle.com/docs/cd/B19306_01/java.102/b14187/chsix.htm#BABJIJEB
当 oracle 已经为此类转换提供了足够的实用程序时,您真的需要用户定义函数 (UDF) java 或其他吗?
该UTL_I18N软件包提供了所有需要的功能。该MAP_CHARSET函数将 ISO 字符集名称映射到 Oracle 字符集名称,然后该RAW_TO_CHAR函数将指定字符集的原始数据转换为VARCHAR2数据库字符集中的字符集。
Oracle 11g R2 架构设置:
create table test (bytes raw(100), chset varchar2(50));
insert into test (bytes, chset) values (hextoraw('454647'), 'iso-8859-1');
Run Code Online (Sandbox Code Playgroud)
查询1:
select t.*
, UTL_I18N.RAW_TO_CHAR( bytes
, UTL_I18N.MAP_CHARSET(chset,0,1)) decoded
from test t
Run Code Online (Sandbox Code Playgroud)
结果:
| BYTES | CHSET | DECODED |
|-------|------------|---------|
| RUZH | iso-8859-1 | EFG |
Run Code Online (Sandbox Code Playgroud)