我试图通过C使用JNI调用java程序。 Java程序基本上是与Hive的JDBC连接。
这是我的代码段
Java程序
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveJdbcClient {
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
//replace "hive" here with the name of the user the queries should run as
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "cloudera", "cloudera");
//Connection con = DriverManager.getConnection("jdbc:hive2://");
Statement stmt = con.createStatement();
String tableName = "testHiveDriverTable";
stmt.execute("drop table if exists " + tableName);
stmt.execute("create table " + tableName + " (key int, value string)");
String sql = "show tables '" + tableName + "'";
System.out.println("Running: " + sql);
ResultSet res = stmt.executeQuery(sql);
if (res.next()) {
System.out.println(res.getString(1));
}
}
}
我的C程序看起来像这样
#include<stdio.h>
#include "jni.h"
int main ( void )
{
char cpath;
JNIEnv *env;
JavaVM *jvm;
int res;
jclass cls;
jmethodID mid = NULL;
//JavaVMOption options;
JavaVMOption options [3];
options[0].optionString="-Djava.class.path=desired-classpath";
options[1].optionString = "-verbose:class";
options[2].optionString = "-Xdebug";
JavaVMInitArgs vm_args;
vm_args.version = JNI_VERSION_1_6;
vm_args.options = options;
vm_args.nOptions = 3;
res = JNI_CreateJavaVM (&jvm, (void **)&env, &vm_args);
if(res < 0 || !env)
printf("\nUnable to Launch JVM\n");
else
printf("**JVM launched successfully**\n");
cls = ( * env) -> FindClass(env, "HiveJdbcClient2");
printf("**cls**:\n",cls);
if (cls!=NULL)
printf("**HiveJdbcClient2 find success**\n");
else
printf("**Something happend with FindClass\n");
mid = (* env) -> GetStaticMethodID (env,cls, "main", "([Ljava/lang/String;)V");
if (mid!=0)
{
printf("**GetStaticMethodID success -test worked**\n");
(* env) -> CallStaticVoidMethod (env, cls, mid, NULL);
}
(* jvm) -> DestroyJavaVM (jvm);
return 0;
}
当我只运行java程序时,jdbc连接似乎工作。但是,当通过C程序调用时,执行将在DriverManager.getConnection()处停止,而不会出现任何错误消息或警告。我检查过hiverserver2正在运行。是否需要像hive-site.xml那样进行其他配置?我使用cloudera CDH virtualbox,因此没有执行任何其他配置。我在这个网站上看到了几个类似的查询和解决方案,但没有任何对我有用....
答案 0 :(得分:0)
我通过捕获JNI调用中的异常来解决问题。顺便说一下,问题是缺少我在-D.Java.path中纠正过的类。