在windows上使用eclipse jdbc连接hive

 1. hive对开发者使用最多的是通过jdbc,odbc等方式连接来完成对hive的操作。本文介绍通过远程windows系统上的eclipse使用jdbc连接hive并对其进行相应的操作。

2. 首先保证windows和hive所在机器能相互连接(ping通)。
3. 在windows上建立一个文件夹,将所用到的包全拷贝到这个文件夹之下:hadoop的有关包,hive的有关包。
4. 在eclipse上新建项目,代码如下:
package org.zju.kasuosuo;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class HiveJdbc{
      private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
 
      /**
       * @param args
       * @throws SQLException
       */
      public static void main(String[] args) throws SQLException {
            try {
                  Class.forName(driverName);
            } catch (ClassNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  System.exit(1);
            }
            Connection con = DriverManager.getConnection(
                        "jdbc:hive://10.13.87.212:10000/records", "hiveuser", "123456");
            Statement stmt = con.createStatement();
            String tableName = "records";
            String sql = "show tables ";
            System.out.println("Running: " + sql);
            ResultSet res = stmt.executeQuery(sql);
            while (res.next()) {
                  System.out.println(res.getString(1));
            }
            // describe table
            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));
            }
            sql ="select* from records";
            res = stmt.executeQuery(sql);
            while(res.next())
            {
                  System.out.println(res.getString(1)+"\t"+res.getInt(2)+"\t"+res.getInt(3));
            }
      }
}
 
5. 这里连接的是records数据库,用户名为hiveuser,密码为123456.在hive上启动hiveserver:
     bin/hive --service hiveserver  不指定端口号,默认端口号为10000
     
6.  在eclipse上运行run on hadoop就可看到执行结果了:
          
7. 很方便吧!!!
posted @ 2012-07-03 11:14  kasuosuo  阅读(2618)  评论(0编辑  收藏  举报