Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.kududb.examples.sample.test;
- import com.cloudera.impala.jdbc41.DataSource;
- import java.io.IOException;
- import java.nio.charset.Charset;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Arrays;
- import java.util.List;
- import java.util.Random;
- import java.util.UUID;
- public class ImpalaJDBCInsertFile {
- private static Connection connectViaDS() throws Exception
- {
- DataSource ds = new com.cloudera.impala.jdbc41.DataSource();
- // ds.setURL("jdbc:impala://swat-audits-1.gce.cloudera.com:21050"); //get
- // a connection refused with this
- // ds.setURL("jdbc:impala://swat-audits-2.gce.cloudera.com:21050");
- ds.setURL("jdbc:impala://swat-kudu-2.gce.cloudera.com:21050");
- return ds.getConnection();
- }
- public static void main(String[] argv) throws SQLException {
- Connection conn = null;
- try {
- conn = connectViaDS();
- } catch (Exception e) {
- System.out.println("Connection Failed! Check output console");
- e.printStackTrace();
- }
- if(conn!=null){
- System.out.println("connection success!!!");
- }else{
- System.out.println("connection failure!!!");
- }
- Statement stmt = null;
- try {
- //create table
- stmt = conn.createStatement();
- //insert into table
- PreparedStatement s=conn.prepareStatement("INSERT INTO " +
- "new_jdbc_impala_table (" +
- "id," +
- "name) " +
- "VALUES (?,?)");
- String file = readFile("test.txt", Charset.defaultCharset());
- for(int i=0;i<10;i++) {
- s.setLong(1, i);
- s.setString(2, file);
- s.executeUpdate();
- System.out.println("Inserted " + i + " records into the table " );
- }
- //query from the table
- String sql2 = "SELECT id, name FROM new_jdbc_impala_table";
- ResultSet rs = stmt.executeQuery(sql2);
- //STEP 5: Extract data from result set
- while(rs.next()){
- //Retrieve by column name
- int id = rs.getInt("id");
- String name = rs.getString("name");
- //Display values
- System.out.print("ID: " + id);
- System.out.print(", Name: " + name);
- }
- rs.close();
- }catch (Exception e){
- e.printStackTrace();
- }finally {
- try {
- if (stmt != null)
- conn.close();
- } catch (SQLException se) {
- }
- try {
- if (conn != null)
- conn.close();
- } catch (SQLException se) {
- se.printStackTrace();
- }
- }
- }
- static String readFile(String path, Charset encoding)
- throws IOException
- {
- byte[] encoded = Files.readAllBytes(Paths.get(path));
- return new String(encoded, encoding);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement