Two days ago, because of the architectural design of the system, to access the hive database directly through Java, for my Java and Hadoop platform Novice, it is really difficult, but fortunately, it is done. The feeling is not very troublesome. This article, as a sentiment record down. (yangyang8848)
I. How hive is accessed
In general, Hive is not directly connected to Java and access, and later came to a sparksql, become a JDBC way to access the connection. First, let me introduce some ways to access from Linux:
1. Telnet to the Linux platform:
2. Into the hive database, we execute a query statement:
As you can see, the system performs the map/reduce operation and finally displays the relevant results.
There is a dry goods OH: Hive Query statement does not support similar to the MySQL paging query, so, here used another way to page, see the picture to learn!
3, below we use Beeline Remote connection Sqarksql then access hive data.
You can see from the top page that the system can query the data correctly.
Second, use Java code for connection access.
If you want to access through Java, first refer to the three jar packages:
<dependency> <groupId>org.apache.hive</groupId> <artifactid>hive-jdbc</ artifactid> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>2.4.1</version> </dependency> <dependency> <groupId> jdk.tools</groupid> <artifactId>jdk.tools</artifactId> <version>1.6</ version> <scope>system</scope> <systempath>${java_home}/lib/tools.jar</ Systempath> </dependency>
Note that the version of the package must be confirmed, do not be too high
If the following error occurs:
org.apache.thrift.TApplicationException:Required field ' Client_protocol ' is unset! Struct:topensessionreq (Client_protocol:null)
The most likely cause is the HIVE-JDBC version of your project and the server inconsistency, replacing the Sing Woo server with a consistent version.
The following access codes have been tested and taken away directly, haha:
public static int Hivejdbc_rowcount (String sql,map<integer,string> params) {try {ResourceBundle RB = Resourcebundle.getbundle ("config"); Class.forName (rb.getstring ("Hivedriverclassname")). newinstance (); Connection conn = drivermanager.getconnection (rb.getstring ("Hiveurl"), Rb.getstring ("Hiveusername"), Rb.getstring (" Hivepassword ")); Java.sql.PreparedStatement PSTSM = conn.preparestatement (sql); for (Integer Key:params.keySet ()) { Pstsm.setstring (Key, Params.get (key));} ResultSet ResultSet = Pstsm.executequery (); int rowNum = 0;if (Resultset.next ()) {rowNum = Resultset.getint (1);} return rowNum; } catch (Exception e) {System.out.println (e); return 0;}}
Hivedriverclassname=org.apache.hive.jdbc.hivedriverhiveurl=jdbc:hive2://192.168.31.243:10000/ defaulthiveusername=roothivepassword=
Java uses JDBC to connect to hive (Sparksql)