Hive学习笔记 6 Hive的JDBC连接

1、配置Hadoop的配置文件/hadoop-2.6.5/etc/hadoop/

 
            hadoop.proxyuser.root.hosts
            127.0.0.1,localhost,pc1
       

    
            hadoop.proxyuser.root.groups
            *
       

2、启动Hive远程服务

./hive --service hiveserver2


3、准备好需要的jar包

/chenjie/hadoop-2.6.5/share/hadoop/common下找到hadoop-common-2.6.5.jar
/chenjie/hadoop-2.6.5/share/hadoop/common/lib下找到commons-collections-3.2.2.jar  commons-logging-1.1.3.jar  slf4j-api-1.7.5.jar

/chenjie/apache-hive-2.3.0-bin/lib下找到hive-common-2.3.0.jar   hive-exec-2.3.0.jar  hive-jdbc-2.3.0.jar   hive-metastore-2.3.0.jar   hive-service-2.3.0.jar

httpclient-4.4.jar  httpcore-4.4.jar   libfb303-0.9.3.jar


4、代码编写

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtils {

	//private static String driver = "org.apache.hadoop.hive.jdbc.HiveDriver";
	private static String driver = "org.apache.hive.jdbc.HiveDriver";
	private static String url = "jdbc:hive2://pc1:10000/default";
	
	//注册驱动
	static{
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	//获取连接
	public static Connection getConnection(){
		try {
			return DriverManager.getConnection(url,"chenjie","chenjie");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	//释放资源
	public static void release(Connection conn,Statement st,ResultSet rs){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				rs = null;
			}
		}
		if(st != null){
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				st = null;
			}
		}
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				conn = null;
			}
		}
	}
}

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;


public class HiveJDBCDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		
		String sql = "select * from student4";
		try {
			//获取连接
			conn = JDBCUtils.getConnection();
			System.out.println("1");
			//创建运行环境
			st = conn.createStatement();
			System.out.println("2");
			//运行HQL
			rs = st.executeQuery(sql);
			System.out.println("3");
			//处理数据
			while(rs.next()){
				int id = rs.getInt("id");
				String name = rs.getString("name");
				int age = rs.getInt("age");
				System.out.println(id+"\t"+name);
			}
			System.out.println("4");
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//JDBCUtils.release(conn, st, rs);
		}
	}

}

5、运行

Hive学习笔记 6 Hive的JDBC连接_第1张图片

你可能感兴趣的:(大数据)