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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。