时间:2021-07-01 10:21:17 帮助过:4人阅读
代码连接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; // 返回所建立的数据库连接 } }
本文出自 “SimpleLife” 博客,请务必保留此出处http://simplelife.blog.51cto.com/9954761/1968412
JDBC连接HIVE
标签:hive jdbc