Create-Drop Database using java in Hive

1. Create database

     A database in Hive is a namespace or a collection of tables. Using JDBC Program we can create database in java is as shown below.

JDBC Program to create database

 

import java.sql.SQLException;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.DriverManager;

 

public class HiveCreateDb {

private static String driverName = “org.apache.hadoop.hive.jdbc.HiveDriver”;

 

public static void main(String[] args) throws SQLException {

// Register driver and create driver instance

 

Class.forName(driverName);

// get connection

Connection con = DriverManager.getConnection(“jdbc:hive://localhost:10000/default”, “”, “”);

Statement stmt = con.createStatement();

stmt.executeQuery(“CREATE DATABASE beyondcorner”);

System.out.println(“Database beyondcorner created successfully.”);

 

con.close();

}

}

Save above program in a file name called “HiveCreateDb.java”

Below commands are used to compile and execute program.

$ javac HiveCreateDb.java

$ java HiveCreateDb

2. Drop database

Drop Database is used to drops all the tables and deletes the database. Using JDBC Program we can drop database in java is as shown below.

 JDBC Program to Drop database

import java.sql.SQLException;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.DriverManager;

 

public class HiveDropDb {

private static String driverName = “org.apache.hadoop.hive.jdbc.HiveDriver”;

public static void main(String[] args) throws SQLException {

// Register driver and create driver instance

Class.forName(driverName);

// get connection

Connection con = DriverManager.getConnection(“jdbc:hive://localhost:10000/default”, “”, “”);

Statement stmt = con.createStatement();

stmt.executeQuery(“DROP DATABASE beyondcorner”);

System.out.println(“Drop beyondcorner database successful.”);

con.close();

}

}

Above program is saved in a file name called “HiveDropDb.java”.

The fallowing commands are used to compile and execute the program.

$ javac HiveDropDb.java

$ java HiveDropDb