java连接hive(未完待续)

版权声明:本文为sam的原创文章,转载请添加出处:http://blog.csdn.net/samed https://blog.csdn.net/samed/article/details/52149851

需求:

java连接hive,执行hql。


本文书写原因:

网上的教程多有纰漏,无法正常运行,特开此文记录。


版本(均为64位):

服务端:

OS:CentOS6.7

java:jdk1.7.0_101

hadoop:2.7.2

hive:2.1.0

mysql:Ver 14.14 Distrib 5.1.73 (mysql-connector-java-5.1.39-bin.jar)

客户端:

OS:windows10

jdk:jdk1.7.0_79

hadoop-common:2.4.0 (maven中配置)

hive-jdbc:2.1.0 (maven中配置)

IDE:eclipse Mars.1 Release (4.5.1)

maven:3.3.9


安装:

主要安装顺序:

SERVER: OS --> JDK --> MYSQL --> MAVEN--> HADOOP --> HIVE

CLIENT: OS --> JDK --> MAVEN --> IDE

# TODO: 具体安装过程会另外开博文记录,敬请留意。


正文:

这个步骤假设所有上述的内容均已经安装完毕。

1. eclipse 中 “文件--新建--其它”,选择 "Maven--Maven Project"。

 

2. 后续的步骤有点罗嗦,不再截图。

     自定义Workspace Location。

     在选择Archetype 的时候选择默认的 “maven-archetype-quickstart” "VERSION:1.1" 。

     输入artifactId 即可完成。

3. 右键pom.xml文件--打开方式--XML EDITOR。

pom.xml文件内容(中文部分请自行删除):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
<!--此处是你的项目基本信息,自行修改-->
  <groupId>Test</groupId>
  <artifactId>TestHive</artifactId>
  <version>0.0.1</version>
  <packaging>jar</packaging>


  <name>TestHive</name>
  <url>http://maven.apache.org</url>


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>


  <dependencies>
<!--依赖,必须的依赖有两个,按照自己的版本不同进行指定吧。
    如果不知道有哪些版本可选,可以上以下网站查询:http://mvnrepository.com/-->
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-common</artifactId>
      <version>2.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hive</groupId>
      <artifactId>hive-jdbc</artifactId>
      <version>2.1.0</version>
    </dependency>
  </dependencies>


<!--如果仅仅是调试用,并非发布用,可以忽略下面build的配置-->
  <build>
<!--可以不进行该行的配置-->
    <defaultGoal>install</defaultGoal>
<!--指定源文件夹-->
    <sourceDirectory>src/main/java</sourceDirectory>
<!--下面这一段意思是将所有依赖一起添加到target目录中,这样就能直接发布了。-->
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <defaultLibBundleDir>lib</defaultLibBundleDir>
          <source>1.5</source>
          <target>1.5</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <classpathPrefix></classpathPrefix>
              <mainClass>com.xx.xx.xx</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>copy</id>
            <phase>install</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>
                ${project.build.directory}
              </outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

4. 创建Client类。

4.1 在src/main/java上右键,创建“包:cn.sam.test.hive”。

4.2 在 cn.sam.test.hive 上右键,创建“类:Client”。

4.3 输入代码:

package cn.sam.test.hive;

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

/**
 * 测试 hive 的客户端连接
 *
 */
public class Client {
    
    // 注意:hive-server2 引用的driver是  org.apache.hive.* 而 hive-server 是 org.apache.hadoop.hive.*
    private static String driverName = "org.apache.hive.jdbc.HiveDriver";
//  private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";

    public static void main(String[] args) throws SQLException {
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        }
        // hive的默认端口是 10000,如果要修改就修改 hive-site.xml 文件的hive.server2.thrift.port 属性值
        // 此处容易遇到坑,网上教程均表示采用默认的 hive 用户和空密码即可,但实际测试是不行的
        // 需要使用能连接hive的系统用户名称和系统用户密码,我是把hive装在 hadoop 用户下的。
        Connection con = DriverManager.getConnection("jdbc:hive2://VirtualBox:10000/default", "hadoop", "hadoop");
//          Connection con = DriverManager.getConnection("jdbc:hive://VirtualBox:10000/default", "hadoop", "hadoop");

        Statement stmt = con.createStatement();
        // 测试的表名 test
        String tableName = "test";
        
        // 如果已经存在就删除
        stmt.execute("drop table if exists " + tableName);
        // 创建这张表
        stmt.execute("create table " + tableName + " (id int, name string) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'");
        
        // 看下表是否存在
        String sql = "show tables '" + tableName + "'";
        System.out.println("Running: " + sql);
        ResultSet res = stmt.executeQuery(sql);
        if (res.next()) {
            System.out.println(res.getString(1));
        }
        
        //看下表结构
        sql = "describe " + tableName;
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);
        while (res.next()) {
            System.out.println(res.getString(1) + "\t" + res.getString(2));
        }
    
        // 加载数据到表里面 -- 方式1: 系统的本地文件
        // 注意: filepath 是服务器上文件的位置,注意这个不是你的电脑!
        String filepath = "/home/hadoop/tmp/testData.txt";
        sql = "load data local inpath '" + filepath + "' into table " + tableName;
        System.out.println("Running: " + sql);
        stmt.execute(sql);

        // 加载数据到表里面 -- 方式2: hadoop上的文件
//      String filepath = "/user/hive/tmp/testData.txt";
//      sql = "load data inpath '" + filepath + "' into table " + tableName;
//      System.out.println("Running: " + sql);
//      stmt.execute(sql);
        
        // 查询数据
        sql = "select * from " + tableName;
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);
        while (res.next()) {
            System.out.println(String.valueOf(res.getInt(1)) + "\t" + res.getString(2));
        }
  }
}  

4.4 别忙着执行这一段代码,先在hive server上创建 /home/hadoop/tmp/testData.txt 文件:

[11:52:42][hadoop@~]$ cat /home/hadoop/tmp/testData.txt
1 sam
2 tom
3 kitty
4 mary

4.5 同时,也将此文件上传到 hadoop 上:

[11:52:42][hadoop@~]$ hdfs dfs -mkdir -p /user/hive/tmp/
[11:52:42][hadoop@~]$ hdfs dfs -put /home/hadoop/tmp/testData.txt /user/hive/tmp/

4.6 执行Client类:

Alt+Shift+x+j    或者    类上右键--运行方式--java应用程序。

如果报错了,建议先build一下pom,因为可能依赖还没有下载捏:

Alt+Shift+x+m    或者    pom.xml文件上右键--运行方式--Maven build,直接点击“运行”即可,无需进行额外配置。

然后就会在maven源下载依赖。

4.7 执行结果:

************************************
省略 SLF4J 及 log4j 初始化信息
************************************
Running: show tables 'test'
test
Running: describe test
id      int
name    string
Running: select * from test
1   sam
2   tom
3   kitty
4   mary



常见错误:


未完待续



猜你喜欢

转载自blog.csdn.net/samed/article/details/52149851