发布网友 发布时间:2022-04-22 18:45
共2个回答
懂视网 时间:2022-04-08 14:04
java.security.MessageDigest; import COM.ibm.db2.app.UDF; public class MD5UDF extends UDF { public static String MD5(String s) { String s1 = new String(""); char hexDigits[] = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘ }; try { byte[] strTemp = s.getBytes(); MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s1 = new String(str); } catch (Exception e) { System.out.println(e.getMessage()); } return "{" + s1 + "}"; } public static void main(String[] args){ System.out.println(MD5("asdf")); } }
3.运行javac编译
javac MD5UDF.java
4.运行jar打包MD5UDF.class 为 MD5UDF.jar
jar cf MD5UDF.jar MD5UDF.class
5.连上数据库,运行安装.jar文件到数据库(C:Documents and SettingsALL USERSApplication DataIBMDB2DB2COPY1functionjarEN 目录下)
db2 connect to sample
db2 "CALL sqlj.install_jar(‘file:E:MD5UDF.jar‘, ‘MD5UDF‘)"
6.登录数据库创建function
DROP FUNCTION BI_MD5; CREATE FUNCTION BI_MD5(VARCHAR(200)) RETURNS VARCHAR(70) EXTERNAL NAME ‘MD5UDF:MD5UDF.MD5‘ FENCED VARIANT NO SQL EXTERNAL ACTION LANGUAGE JAVA PARAMETER STYLE JAVA
7.调用测试
select bi_MD5(‘12345‘) from sysibm.dual
OK!
结论:
1.安装、删除、替换jar文件
db2 "CALL sqlj.install_jar(‘file:D:someBookesJavaMD5UDF2.jar‘, ‘BIMD5‘)"
db2 "CALL sqlj.remove_jar(‘BIMD5‘)"
db2 "CALL sqlj.replace_jar(‘file:E:mydb2mylog.jar‘, ‘BIMD5‘)"
2.刷新已经调用的jar或class,不用重启实例就生效:
db2 "CALL SQLJ.REFRESH_CLASSES()"
3.调用的Java方式必须是静态的。
4.编译成jar包的SDK版本必须和db2的版本相符
否则会报错
参考文章:
db2使用Java存储过程实现MD5函数
标签:
热心网友 时间:2022-04-08 11:12
import java.security.MessageDigest;
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public static void main(String[] args){
String s= "20160408dehui013691632869";
System.out.println(MD5Encode(s,null));
}
}