大数据系列hive——jdbc

一、简介

       hive可以通过命令行执行hql,它也提供了相应的jdbc驱动,从而可以使用jdbc api进行代码的编写。

二、HiveServer2

       hive的服务,只有开启了hiveServer2,客户端才能通过jdbc连接上hive

  • 配置

       修改hive-site.xml,其中相关的配置项如下

       hive.server2.thrift.min.worker.threads:最小的工作线程数

       hive.server2.thrift.max.worker.threads:最大的工作线程数

       hive.server2.thrift.port:thrift的端口号,默认为10000

       hive.server2.thrift.bind.host:thrift主机名

  • 启动

        方式一:

       $HIVE_HOME/bin/hiveserver2

        方式二:

       $HIVE_HOME/bin/hive --service hiverserver2

三、Beeline

       Beeline是hive jdbc的客户端,可以通过它来连接jdbc,并通过命令执行hql。我们可以用它来验证是否可以连接上hive jdbc。

       Beeline的成功启动需要如下条件

       1、MetaStore

       MetaStore默认在启动hiveServer2时会自动启动,手动启动命令为$HIVE_HOME/bin/hive --service metastore &

       2、Hadoop

       3、HiveServer2

       启动命令:$HIVE_HOME/bin/beeline

       连接jdbc命令:!connect jdbc:hive2:/ip或者主机名:端口号(默认为10000)

四、错误处理

       在执行!connect命令时有可能报如下错误

        解决办法:

        修改hadoop的core-site.xml

<property>
    <name>hadoop.proxyuser.root.hosts</name>
    <value>*</value>
</property>

<property>
    <name>hadoop.proxyuser.root.groups</name>
    <value>*</value>
</property>

        重启hadoop

五、代码

public class HiveDemo {

	private static String driveName = "org.apache.hive.jdbc.HiveDriver";
	
	private static String url = "jdbc:hive2://192.168.160.66:10000/default";
	
	public static void main(String[] args) {
		
		Connection conn = null;
		Statement statement = null;
		ResultSet result = null;
		
		try {
			
			Class.forName(driveName);
			conn = DriverManager.getConnection(url, "root", "");
			statement = conn.createStatement();
			String sql = "show tables";
			result = statement.executeQuery(sql);
			while(result.next()) {
				System.out.println(result.getString(1));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
			Optional
			.ofNullable(result)
			.ifPresent(r->{
				try {
					r.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			});
			
			Optional
			.ofNullable(statement)
			.ifPresent(s->{
				try {
					s.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			});
			
			Optional
			.ofNullable(conn)
			.ifPresent(c->{
				try {
					c.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			});
			
		}
	}
	
}

猜你喜欢

转载自blog.csdn.net/guduyishuai/article/details/81698522