Created
May 23, 2017 05:41
-
-
Save jychstar/5d7603ad07ced58d15828dac89255036 to your computer and use it in GitHub Desktop.
HIve JDBC example codes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package etl; | |
import java.sql.ResultSet; | |
import java.sql.ResultSetMetaData; | |
import java.sql.SQLException; | |
import java.sql.Connection; | |
import java.sql.Statement; | |
import java.sql.DriverManager; | |
public class etl { | |
private static String driverName = "org.apache.hive.jdbc.HiveDriver"; | |
public static void main(String[] args) throws SQLException { | |
try {Class.forName(driverName);} | |
catch(ClassNotFoundException ex) { | |
System.out.println("Error: unable to load driver class!"); | |
System.exit(1); | |
} | |
// get connection, user and password are ignored in non-secured mode | |
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "cloudera", "cloudera"); | |
Statement stmt = con.createStatement(); | |
// declare variables | |
String tableName = "employee"; | |
String sql; | |
ResultSet res; | |
ResultSetMetaData metadata; | |
// example query | |
sql = "describe " + tableName ; | |
System.out.println("Running 1: " + sql); | |
res = stmt.executeQuery(sql); | |
while (res.next()) | |
{System.out.println(res.getString(1)+"\t"+ res.getString(2));} | |
System.out.println(); | |
// manually print all columns and results | |
sql = "SELECT * FROM employee e"; | |
res = stmt.executeQuery(sql); | |
System.out.println("Running 2: " + sql); | |
System.out.println(" ID \t Name \t Salary \t Designation "); | |
while (res.next()) { | |
System.out.println(res.getInt(1) + " " + res.getString(2) + " " + res.getDouble(3) + " " + res.getString(4)); | |
} | |
System.out.println(); | |
// automatically print all columns and results | |
System.out.println("Running 3:"+sql); | |
res = stmt.executeQuery(sql); | |
metadata = res.getMetaData(); | |
int columnCount = metadata.getColumnCount(); | |
for (int i = 1; i <= columnCount; i++) | |
{ System.out.print(metadata.getColumnName(i) + "\t "); } | |
System.out.println(); | |
while (res.next()) | |
{ String row = ""; | |
for (int i = 1; i <= columnCount; i++) | |
{ row += res.getString(i) + ", "; } | |
System.out.println(row); | |
} | |
con.close(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment