01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
package
org.impala.demo;
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.ResultSet;
import
java.sql.SQLException;
import
java.sql.Statement;
import
org.apache.log4j.Logger;
public
class
ImpalaJdbcClient {
private
static
String driverName =
"org.apache.hive.jdbc.HiveDriver"
;
private
static
String url =
"jdbc:hive2://172.31.25.8:21050/qyk_test;auth=noSasl"
;
private
static
String user =
"impala"
;
private
static
String password =
""
;
private
static
final
Logger log = Logger.getLogger(ImpalaJdbcClient.
class
);
public
static
void
main(String[] args) {
try
{
Class.forName(driverName);
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
// 创建的表名
String tableName =
"user"
;
stmt.execute(
"drop table if exists "
+ tableName);
stmt.execute(
"create table "
+ tableName
+
" (key int, value string) row format delimited fields terminated by '\t'"
);
// show tables
String sql =
"show tables '"
+ tableName +
"'"
;
System.out.println(
"Running: "
+ sql);
ResultSet res = stmt.executeQuery(sql);
if
(res.next()) {
System.out.println(res.getString(
1
));
}
// describe table
sql =
"describe "
+ tableName;
System.out.println(
"Running: "
+ sql);
res = stmt.executeQuery(sql);
while
(res.next()) {
System.out.println(res.getString(
1
) +
"\t"
+ res.getString(
2
));
}
// load data into table
// NOTE: filepath has to be local to the hive server
// NOTE: /tmp/a.txt is a ctrl-A separated file with two fields per
// line
String filepath =
"/tmp/userinfo.txt"
;
sql =
"load data inpath '"
+ filepath +
"' into table "
+ tableName;
System.out.println(
"Running: "
+ sql);
stmt.execute(sql);
// select * query
sql =
"select * from "
+ tableName;
System.out.println(
"Running: "
+ sql);
res = stmt.executeQuery(sql);
while
(res.next()) {
System.out.println(String.valueOf(res.getInt(
1
)) +
"\t"
+ res.getString(
2
));
}
// regular hive query
sql =
"select count(1) from "
+ tableName;
System.out.println(
"Running: "
+ sql);
res = stmt.executeQuery(sql);
while
(res.next()) {
System.out.println(res.getString(
1
));
}
}
catch
(ClassNotFoundException e) {
e.printStackTrace();
log.error(driverName +
" not found!"
, e);
System.exit(
1
);
}
catch
(SQLException e) {
e.printStackTrace();
log.error(
"Connection error!"
, e);
System.exit(
1
);
}
}
}
|
1
2
3
4
|
1
zhangshan
2
lisi
3
wangwu
5
baidu
|