Hive应用实验-使用Java管理Hive数据

2021-11-21  本文已影响0人  水又icf

1.环境变量配置

请参考Hive应用实验-安装HIVE并配置Mysql远程MetaData

2.示例代码

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

public class HiveCreateTable {
    private static String driverName = "org.apache.hive.jdbc.HiveDriver";

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Class.forName(driverName);
        Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default","hive","hive");
        Statement statement = con.createStatement();

        statement.executeQuery("create table if not exists "
            +"employee2(eid int ,name String,salary String, destination String) "
            +"comment 'Employee details' "
            +"row format delimited "
            +"fields terminated by '\t' "
            +"lines terminated by '\n' "
            +"stored as textfile ");

        System.out.println("ok!");
        con.close();
    }
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

public class HiveTableTest{
    
    private static String diverName = "org.apache.hive.jdbc.HiveDriver";

    public static void main(String[] args) throws Exception{
        System.out.println("hello!");
        /*加载驱动*/
        Class.forName(diverName);
        /*创建连接*/
        Connection conn = DriverManager.getConnection("jdbc:hive2://192.168.70.101:10000/default","hive","hive");
        /*创建查询对象*/
        Statement state = conn.createStatement();
        /*执行查询*/
        ResultSet rs = state.executeQuery("select * from employee");

        while(rs.next()){
            int eid = rs.getInt("eid");//根据字段名获取数据
            String name = rs.getString(2);//根据列序号获取数据,从1开始
            System.out.printf("ID:%d\tNAME:%s\n",eid,name);
        }

        /*处理查询结果*/
        System.out.println("ok!");

        /*关闭连接*/
        conn.close();
    }

}

3.常用Java命令

javac Test.java
java Test

注:
Java主类的类名需要跟文件名完全一致,大小写敏感

上一篇 下一篇

猜你喜欢

热点阅读