JDBC連接Greenplum數據庫,封裝了增刪改查


要啟動好gp服務,再嘗試連接

192.168.94.135是主節點(master)的ip

驅動Jar包在官網獲取

嫌麻煩,可以直接用我在網盤分享的Jar包,版本較老

鏈接:https://pan.baidu.com/s/1gVsxupUNUPXuewYlXHmgyw
提取碼:bq1c

 

package com.advance.JDBC;

import java.sql.*;
import java.util.*;

/**
 * @Auther: 谷天樂
 * @Date: 2018/11/14 16:47
 * @Description:
 * 通過JDBC連接Greenplum
 */
public class Connect_Greenplum {
    //表信息
    static class TbInfo
    {
        //分布鍵
        String id;
        //日期
        String date;
        //價格
        String amt;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public String getAmt() {
            return amt;
        }

        public void setAmt(String amt) {
            this.amt = amt;
        }
    }

    //表結構
    static class TbStructure{
        //appendonly屬性
        boolean appendonly = true;
        //壓縮類型
        String compresstype = "zlib";
        //壓縮級別
        int compresslevel = 5;
        //表的列和類型,用逗號分隔
        String columnInfo;
        //表名稱
        String tbName;
        //分布鍵
        String distributedKey;

        public String getCompresstype() {
            return compresstype;
        }

        public void setCompresstype(String compresstype) {
            this.compresstype = compresstype;
        }

        public boolean isAppendonly() {
            return appendonly;
        }

        public void setAppendonly(boolean appendonly) {
            this.appendonly = appendonly;
        }

        public int getCompresslevel() {
            return compresslevel;
        }

        public void setCompresslevel(int compresslevel) {
            this.compresslevel = compresslevel;
        }

        public String getColumnInfo() {
            return columnInfo;
        }

        public void setColumnInfo(String columnInfo) {
            this.columnInfo = columnInfo;
        }

        public String getTbName() {
            return tbName;
        }

        public void setTbName(String tbName) {
            this.tbName = tbName;
        }

        public String getDistributedKey() {
            return distributedKey;
        }

        public void setDistributedKey(String distributedKey) {
            this.distributedKey = distributedKey;
        }
    }

    //三大核心接口
    private static Connection conn = null;
    private static PreparedStatement pstmt = null;
    private static ResultSet rs = null;

    //連接數據庫
    public static Connection connectGreenplum() throws ClassNotFoundException, SQLException {
        // URL
        String url = "jdbc:pivotal:greenplum://192.168.94.135:5432;DatabaseName=testdw";
        // 數據庫用戶名
        String username = "gpadmin";
        // 數據庫密碼
        String password = "gpadmin";
        // 加載驅動
        Class.forName("com.pivotal.jdbc.GreenplumDriver");
        // 獲取連接
        conn = DriverManager.getConnection(url, username, password);
        return conn;
    }

    //關閉數據庫連接
    public static  void closeConnection(){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(pstmt!=null){
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //查詢方法
    public static ResultSet query(String sql) throws SQLException, ClassNotFoundException {
        Connection conn = connectGreenplum();
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery();
        return rs;
    }

    //通用增刪改
    public static void update(String sql,Object []values) throws SQLException, ClassNotFoundException {
        //獲取數據庫鏈接
        conn=connectGreenplum();
        try {
            //預編譯
            pstmt=conn.prepareStatement(sql);
            //獲取ParameterMetaData()對象
            ParameterMetaData pmd=pstmt.getParameterMetaData();
            //獲取參數個數
            int number=pmd.getParameterCount();
            //循環設置參數值
            for (int i = 1; i <=number; i++) {
                pstmt.setObject(i, values[i-1]);
            }
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            closeConnection();
        }
    }



    //新增方法
    public static Integer insert(String sql,TbInfo tbInfo) throws SQLException, ClassNotFoundException {
        Connection conn = connectGreenplum();
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,tbInfo.getId());
        pstmt.setString(2,tbInfo.getDate());
        pstmt.setString(3,tbInfo.getAmt());
        Integer rs = pstmt.executeUpdate();
        return rs;
    }

    //刪除方法
    public static Integer delete(String sql,TbInfo tbInfo) throws SQLException, ClassNotFoundException {
        conn = connectGreenplum();
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,tbInfo.getId());
        Integer rs = pstmt.executeUpdate();
        return rs;
    }

    //修改方法
    public static Integer update(String sql,TbInfo tbInfo) throws SQLException, ClassNotFoundException {
        conn = connectGreenplum();
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,tbInfo.getAmt());
        pstmt.setString(2,tbInfo.getId());
        Integer rs = pstmt.executeUpdate();
        return rs;
    }

    //輸出
    public static void output(ResultSet rs) throws SQLException {
        while(rs.next())
        {
            System.out.println(
                    "id:"+rs.getString("id")+
                    " 日期:"+rs.getString("date")+
                    " 價格:"+rs.getString("amt"));
        }
    }

    //ResultSet轉換成list
    public static List resultSetToList(ResultSet rs) throws java.sql.SQLException {
        if (rs == null)
            return Collections.EMPTY_LIST;
        ResultSetMetaData md = rs.getMetaData(); //得到結果集(rs)的結構信息,比如字段數、字段名等
        int columnCount = md.getColumnCount(); //返回此 ResultSet 對象中的列數
        List list = new ArrayList();
        Map rowData;
        while (rs.next()) {
            rowData = new HashMap(columnCount);
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnName(i), rs.getObject(i));
            }
            list.add(rowData);
            System.out.println("list:" + list.toString());
        }
        return list;
    }

    //刪除表
    public static Integer dropTable(String tableName) throws SQLException, ClassNotFoundException {
        conn = connectGreenplum();
        String sql = "DROP TABLE if EXISTS "+tableName+";";
        pstmt = conn.prepareStatement(sql);
        Integer rs = pstmt.executeUpdate();
        return rs;
    }

    //刪除外部表
    public static Integer dropExternalTable(String tableName) throws SQLException, ClassNotFoundException {
        conn = connectGreenplum();
        String sql = "DROP EXTERNAL TABLE if EXISTS "+tableName+";";
        pstmt = conn.prepareStatement(sql);
        Integer rs = pstmt.executeUpdate();
        return rs;
    }

    //創建表
    public static Integer createTable(String tbName,String columnInfo,String distributedKey) throws SQLException, ClassNotFoundException {
        conn = connectGreenplum();
        TbStructure tbStructure = new TbStructure();
        String sql = "CREATE TABLE "+tbName+" ("+columnInfo+")\n" +
                "WITH (appendonly="+tbStructure.isAppendonly()+", " +
                "compresstype="+tbStructure.getCompresstype()+",\n" +
                "compresslevel="+tbStructure.getCompresslevel()+")   DISTRIBUTED BY ("+distributedKey+");";
        pstmt = conn.prepareStatement(sql);
        Integer rs = pstmt.executeUpdate();
        return rs;
    }

    //創建可讀外部表,需要啟動gpfdist服務,再導入csv
    public static Integer createExternalTable(String tbName,String columnInfo,String location,
                                              String format,String delimiter) throws SQLException, ClassNotFoundException {
        conn = connectGreenplum();
        String sql = "CREATE EXTERNAL TABLE "+tbName+" ("+columnInfo+") \n" +
                "LOCATION ("+"\'"+location+"\'"+")\n" +
                "FORMAT "+"\'"+format+"\'"+" (DELIMITER "+"\'"+delimiter+"\'"+")\n";
        pstmt = conn.prepareStatement(sql);
        Integer rs = pstmt.executeUpdate();
        System.out.println("成功創建外部表");
        return rs;
    }

    public static void main(String[] args) {
        try {
            // 插入功能
            /*String insertSql = "insert into tb_cp_02 values(?,?,?);";
            TbInfo tbInfo1 = new TbInfo();
            tbInfo1.setId("7");
            tbInfo1.setDate("2013-06-01");
            tbInfo1.setAmt("500.00");
            insert(insertSql,tbInfo1);*/
            // 刪除功能
            /*String deleteSql = "delete from tb_cp_02 where id = ?";
            TbInfo tbInfo1 = new TbInfo();
            tbInfo1.setId("2");
            delete(deleteSql,tbInfo1);*/

            // 修改功能
            /*String updateSql = "update tb_cp_02 set amt = ? where id = ?";
            TbInfo tbInfo1 = new TbInfo();
            tbInfo1.setId("3");
            tbInfo1.setAmt("1001.0");
            update(updateSql,tbInfo1);*/

            /*for (TbInfo tb:tbInfos
                 ) {
                System.out.println(tb.getId());
            }*/
            //dropTable("tb_tag_1_read");
            //createTable("foo","a int, b text","a");
//            dropExternalTable("tb_tag_1_read");
//            createExternalTable("tb_tag_1_read","id text,school_commun_flag text,wire_tv_flag text",
//                    "gpfdist://mdw:8081/20190108.csv","CSV",";");
            update("update tb_cp_02 set amt = ? where id = ?",new Object[]{"1000","7"});


            //查詢
            String selectSql = "select * from tb_cp_02";
            ResultSet rs = query(selectSql);
            List<TbInfo> tbInfos = resultSetToList(rs);
            Iterator it = tbInfos.iterator();
            while(it.hasNext()) {
                Map hm = (Map)it.next();
                System.out.println(hm.get("id"));
                System.out.println(hm.get("amt"));
                System.out.println(hm.get("date"));
            }
            closeConnection();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM