您好,登錄后才能下訂單哦!
hive是大數據技術簇中進行數據倉庫應用的基礎組件,是其它類似數據倉庫應用的對比基準。基礎的數據操作我們可以通過腳本方式以hive-client進行處理。若需要開發應用程序,則需要使用hive的jdbc驅動進行連接.
代碼連接hive需要先啟動hive的metastore和hiveserver2
hive --service metastore & hive --service hiveserver2 &
其中hive-site.xml的配置為:
<configuration> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:mysql://192.168.174.131:3306/hive?createDatabaseIfNotExist=true</value> <description>JDBC connect string for a JDBC metastore</description> </property> <property> <name>javax.jdo.option.ConnectionDriverName</name> <value>com.mysql.jdbc.Driver</value> <description>Driver class name for a JDBC metastore</description> </property> <property> <name>javax.jdo.option.ConnectionUserName</name> <value>root</value> <description>username to use against metastore database</description> </property> <property> <name>javax.jdo.option.ConnectionPassword</name> <value>123456</value> <description>password to use against metastore database</description> </property> <property> <name>hive.metastore.uris</name> <value>thrift://192.168.174.131:9083</value> </property> <property> <name>hive.support.sql11.reserved.keywords</name> <value>false</value> </property> </configuration>
代碼要想連接hive需要添加兩個依賴:
<!--S:連接hive --> <!-- https://mvnrepository.com/artifact/org.apache.hive/hive-jdbc --> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-jdbc</artifactId> <!--注:此處的版本要和hive的lib中對應jar包的版本一致--> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>2.6.4</version> </dependency> <!--E:連接hive -->
代碼演示:
package com.fwmagic.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.mysql.jdbc.Statement; public class JdbcHive { private static Connection conn; private static Statement st; public static void main(String[] args) throws Exception { Connection connection = getConnection(); System.out.println("connection:"+connection); String sql = "show tables"; PreparedStatement prepareStatement = connection.prepareStatement(sql); ResultSet rs = prepareStatement.executeQuery(); while(rs.next()){ String db = rs.getString(1); System.out.println(db); } } /* 獲取數據庫連接的函數 */ private static Connection getConnection() { Connection con = null; // 創建用于連接數據庫的Connection對象 try { Class.forName("org.apache.hive.jdbc.HiveDriver");// 加載hive2數據驅動 con = DriverManager.getConnection( "jdbc:hive2://192.168.174.131:10000/default", "root", null);// 創建數據連接 } catch (Exception e) { System.out.println("hive數據庫連接失敗" + e.getMessage()); } return con; // 返回所建立的數據庫連接 } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。