How to use java api to send hbase shell command directly like jdbc?
public static void main(String args[]) {
// get Connection to connect hbase
Connection conn = ....;
// hbase shell command
String cmd = "get 't1','r1'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(cmd);
while(rs.next()) {
...
}
}
if there is no java api for this, is there another way to achieve the goal?
Please note that, Phoenix can execute queries in jdbc style... If you want to execute get commands then you can use Hbase java client api directly. Its not common practice to execute from java through shell.
If you still want to do it from java prepare gets or list of commands in a text file and using RunTime.execute
you can execute hbase shell <yourhbaseshelllcommands.txt>
see my answer1 or answer2 this to do that. I have done that for spark submit and mapreduce jobs. you can use the same method for your hbase shell execution which was described above.
another way to achieve the goal
To access Hbase in SQL way you can use Phoenix.
- https://phoenix.apache.org/faq.html
- see this
Also you can check with Impala or hive.
JDBC Client Driver :
import java.sql.*;
public class PhoenixExample {
public static void main(String[] args) {
// Create variables
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
// Connect to the database
connection = DriverManager.getConnection("jdbc:phoenix:localhost");
// Create a JDBC statement
statement = connection.createStatement();
// Execute our statements
statement.executeUpdate("create table javatest (mykey integer not null primary key, mycolumn varchar)");
statement.executeUpdate("upsert into javatest values (1,'Hello')");
statement.executeUpdate("upsert into javatest values (2,'Java Application')");
connection.commit();
// Query for table
ps = connection.prepareStatement("select * from javatest");
rs = ps.executeQuery();
System.out.println("Table Values");
while(rs.next()) {
Integer myKey = rs.getInt(1);
String myColumn = rs.getString(2);
System.out.println("\tRow: " + myKey + " = " + myColumn);
}
}
catch(SQLException e) {
e.printStackTrace();
}
finally {
if(ps != null) {
try {
ps.close();
}
catch(Exception e) {}
}
if(rs != null) {
try {
rs.close();
}
catch(Exception e) {}
}
if(statement != null) {
try {
statement.close();
}
catch(Exception e) {}
}
if(connection != null) {
try {
connection.close();
}
catch(Exception e) {}
}
}
}
}
If you are using maven below are dependencies...
<dependency>
<groupId>org.apache.phoenix</groupId>
<artifactId>phoenix-core</artifactId>
<version>4.6.0-HBase-1.1</version>
</dependency>