Hive应用(6.1)Java程序操作Hive

Hive提供了jdbc驱动,所以很多常见的ORM框架可以使用,这里仅仅是一个简单的示例:

  1. 引入hive-jdbc

    1
    2
    3
    4
    5
    <dependency>
    <groupId>org.apache.hive</groupId>
    <artifactId>hive-jdbc</artifactId>
    <version>1.1.0</version>
    </dependency>
  2. 编写代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    package info.aviraer.demo.bigdata.core.hive;

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

    public class App {

    private static final String DRIVER = "org.apache.hive.jdbc.HiveDriver";
    private static final String DB_URL = "jdbc:hive2://cdh3:10000/test";

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
    Class.forName(DRIVER);
    Connection connection = DriverManager.getConnection(DB_URL, "username", "password");
    PreparedStatement statement = connection.prepareStatement("select * from users limit ?");
    statement.setInt(1, 10);
    ResultSet resultSet = statement.executeQuery();
    while (resultSet.next()) {
    System.out.println(resultSet.getString(1) + "\t" + resultSet.getString(2) + "\t" +resultSet.getString(3) + "\t");
    }
    connection.close();
    }
    }