Java 使用Hivejdbc连接Hive

虚拟机中:

  • 启动:hiveserver2
  • 启动:beeline
  • 连接:hiveserver2

创建Maven项目:

  1. 引入依赖:
<dependency> 
        <groupId>org.apache.hivegroupId> 
        <artifactId>hive-jdbcartifactId> 
        <version>1.2.1version> 
dependency> 
    
<dependency> 
        <groupId>org.apache.hadoopgroupId> 
        <artifactId>hadoop-commonartifactId> 
       <version>2.4.1version> 
dependency> 
   
<dependency> 
       <groupId>jdk.toolsgroupId> 
       <artifactId>jdk.toolsartifactId> 
       <version>1.6version> 
       <scope>systemscope> 
       <systemPath>${JAVA_HOME}/lib/tools.jarsystemPath> 
   dependency> 

  1. 创建连接:

import java.sql.Connection;import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
 
public class test {
    private static String driverName ="org.apache.hive.jdbc.HiveDriver";   // 此Class 位于 hive-jdbc的jar包下
    private static String Url="jdbc:hive2://222.22.91.81:10000/";    //填写hive的IP,之前在配置文件中配置的IP
    private static Connection conn;
    public static Connection getConnnection()
    {
        try
               {
                  Class.forName(driverName);
                  conn = DriverManager.getConnection(Url,"","");        //只是连接hive, 用户名可不传
               }
        catch(ClassNotFoundException e)  {
                   e.printStackTrace();
                   System.exit(1);
                }
         catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static PreparedStatement prepare(Connection conn, String sql) {
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ps;
    }
}
  1. 测试使用:
import java.sql.Connection;import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class test2 {
    private static Connection conn=test.getConnnection();
    private static PreparedStatement ps;
    private static ResultSet rs;
    public static void getAll(String tablename)
    {
        String sql="select * from "+tablename;
        System.out.println(sql);
        try {
            ps=test.prepare(conn, sql);
            rs=ps.executeQuery();
            int columns=rs.getMetaData().getColumnCount();
            while(rs.next())
            {
                for(int i=1;i<=columns;i++)
                {
                    System.out.print(rs.getString(i));  
                    System.out.print("\t\t");
                }
                System.out.println();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
    }

	public static void main(String[] args) { 
		String tablename="students";
        test2.getAll(tablename);
    }
 
}

你可能感兴趣的:(hive,hive)