首先需要实现hive能够远程访问:配置见
https://blog.csdn.net/u011066470/article/details/91998651
Java代码:
package com.meboth.hive.connection.hbase.utils;
import java.sql.*;
/**
* @className JDBCToHiveUtils
* @Description TODO
* @Author admin
* @Date 2019/6/15 15:59
* @Version 1.0
**/
public class JDBCToHiveUtils {
private static String driverName ="org.apache.hive.jdbc.HiveDriver"; // 此Class 位于 hive-jdbc的jar包下//org.apache.hive.jdbc.HiveDriver
private static String Url="jdbc:hive2://10.1.11.100:10000/hv_user_profile"; //填写hive的IP,之前在配置文件中配置的IP
private static String uName="www";
private static String uPwd="123456";
private static Connection conn=null;
private static ResultSet rs=null;
private static PreparedStatement ps = null;
/**
* 开启连接
* @return
*/
public static Connection initConnnection()
{
try
{
Class.forName(driverName);
conn = DriverManager.getConnection(Url,uName,uPwd); //只是连接hive, 用户名可不传
}
catch(ClassNotFoundException e) {
e.printStackTrace();
System.out.println("数据库连接失败!!!!!!!!!!!");
System.exit(1);
}
catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 查询数据
* @param sql
* @param obj
* @return
*/
public static ResultSet queryData(String sql, Object[] obj) {
try {
if(conn==null){
initConnnection();
}
ps = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
ps.setObject(i + 1, obj[i]);
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
/**
*添加,修改和删除
* @param sql
* @param obj
* @return
*/
public static int updateAndDeleteData(String sql, Object[] obj) {
int i = 0;
try {
if(conn==null){
initConnnection();
}
ps = conn.prepareStatement(sql);
for (int j = 0; j < obj.length; j++) {
ps.setObject(j + 1, obj[j]);
}
i = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closePs();
}
return i;
}
public static void closePs(){
if ( ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void CloseConnection(){
if ( ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
调用:
package com.meboth.hive.connection.hbase.hive; import com.meboth.hive.connection.hbase.utils.JDBCToHiveUtils; import com.meboth.hive.connection.hbase.utils.QueryHiveUtils; /** * @className HiveApp * @Description TODO * @Author admin * @Date 2019/6/15 15:58 * @Version 1.0 * //https://blog.csdn.net/u010745505/article/details/72770958 * //https://blog.csdn.net/HG_Harvey/article/details/77688703 hive java api * //https://www.cnblogs.com/lay2017/p/9973523.html **/ public class HiveApp { public static void main(String args[]){ //初始化连接 JDBCToHiveUtils.initConnnection(); //查询数据 String tableName="hv_users"; String sql="select * from "+tableName+" limit 0,10"; Object obj[]={}; QueryHiveUtils.queryHiveData(tableName,sql,obj); JDBCToHiveUtils.CloseConnection(); } }