hive的jdbc
hive的jdbc和base上的phoenix組件使用一樣,同樣需要連接到一個服務上,只不phoenix是通過zookeeper連接的,而hive的2.X之後需要使用hiveserver2 (後臺需要單獨啓動hiveserver2),它的調用過程和phoenix一模一樣!
需要配置一下hadoop的core-site.xml
<property>
<name>hadoop.proxyuser.root.hosts</name>
<value>*</value>
</property>
<property>
<name>hadoop.proxyuser.root.groups</name>
<value>*</value>
</property>
操作過程,啓動後臺hiveserver2
項目中導入hive下的jdbc中的jar包
package demo.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCUtils
{
//連接phoenix
private static String driver = "org.apache.hive.jdbc.HiveDriver";
//ZooKeeper的地址
private static String url = "jdbc:hive2://192.168.112.111:10000/default";
//註冊驅動
static{
try
{
Class.forName(driver);
} catch (Exception e)
{
e.printStackTrace();
}
}
//獲取數據連接
public static Connection getConection(){
try
{
Connection connection = DriverManager.getConnection(url);
return connection;
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
//關閉鏈接
public static void closeConn(Connection conn,Statement statement,ResultSet result){
if (result!=null)
{
try
{
result.close();
} catch (Exception e)
{
e.printStackTrace();
}finally {
result=null;
}
}
if (statement!=null)
{
try
{
statement.close();
} catch (Exception e)
{
e.printStackTrace();
}finally {
statement=null;
}
}
if (conn!=null)
{
try
{
conn.close();
} catch (Exception e)
{
e.printStackTrace();
}finally {
conn=null;
}
}
}
}
package demo.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestMain
{
public static void main(String[] args) throws SQLException {
String sql="select * from emp";
Connection conn= null;
Statement st=null;
ResultSet rs=null;
try
{
Connection conection = JDBCUtils.getConection();
st=conection.createStatement();
rs = st.executeQuery(sql);
while (rs.next())
{
//姓名和薪水
String ename = rs.getString("ename");
double sal = rs.getDouble("sal");
System.out.println(ename+"\t"+sal);
}
} catch (Exception e)
{
e.printStackTrace();
}finally {
JDBCUtils.closeConn(conn, st, rs);
}
}
}