美文网首页
Hive应用实验-使用Java管理Hive数据

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

作者: 水又icf | 来源:发表于2021-11-21 16:23 被阅读0次

    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主类的类名需要跟文件名完全一致,大小写敏感

    相关文章

      网友评论

          本文标题:Hive应用实验-使用Java管理Hive数据

          本文链接:https://www.haomeiwen.com/subject/gftmtrtx.html