JDBC编写步骤
JDBCTest.java
import java.sql.*;
public class JdbcTest {
public static void main(String[] args) throws SQLException {
try {
1.加载驱动 (这里连接的是hive:org.apache.hive.jdbc.HiveDriver)
Class.forName("org.apache.hive.jdbc.HiveDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
2.建立连接 (与数据建立链接:“jdbc:hive2://192.168.230.131:10000/test”,“root”,“root”)
//通信端口 :50070 9000 50090 8080 8088 3306 22 2181 2888/3888 10000
Connection con = DriverManager.getConnection("jdbc:hive2://192.168.230.131:10000/test","root","root");
3.引入接口
Statement sta = con.createStatement();
4.编写hql语句(类似于sql)用接口封装的excute 和 executeQuery方法分别进行添加和查询操作
String tableName = "jdbcTest2";
sta.execute("drop table if exists"+tableName);
sta.execute("CREATE table "+tableName+"(key int,value String)");
System.out.println("Create table success!");
//show tables
String sql = "show tables '"+tableName+"'";
System.out.println("Running: "+sql);
ResultSet res = sta.executeQuery(sql);
if(res.next()){
System.out.println(res.getString(1));
}
//describe table
sql = "describe "+tableName;
System.out.println("Running: "+sql);
res = sta.executeQuery(sql);
while(res.next()){
System.out.println(res.getString(1)+"\t"+res.getString(2));
}
sql ="select * from "+tableName;
res = sta.executeQuery(sql);
while(res.next()){
System.out.println(String.valueOf(res.getInt(1)+"\t"+res.getString(2)));
}
sql = "select count(1) from "+tableName;
System.out.println("Running: "+sql);
res = sta.executeQuery(sql);
while(res.next()){
System.out.println(res.getString(1));
}
}
}