本文主要是介绍ODPS的Java连接(2),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
maven
<dependency><groupId>com.aliyun.odps</groupId><artifactId>odps-jdbc</artifactId><version>3.0.1</version>
</dependency>
正文
package org.apache.dolphinscheduler.common.utils;import com.aliyun.odps.*;
import com.aliyun.odps.account.Account;
import com.aliyun.odps.account.AliyunAccount;
import com.aliyun.odps.data.Record;
import com.aliyun.odps.task.SQLTask;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class OdpsUtil {/*** odps连接* @param endPoint 地址* @param accessId 用户名* @param accessKey 密码* @param project 数据库名称* @return*/public static Odps getConn(String endPoint, String accessId, String accessKey, String project) {Account account = new AliyunAccount(accessId, accessKey);Odps odps = new Odps(account);odps.setEndpoint(endPoint);odps.setDefaultProject(project);return odps;}/*** 获取OPDS的tables* @param stmt opds已连接对象* @return*/public ArrayList<Map<String, String>> showTables(Odps stmt) {ArrayList<Map<String, String>> tablelist = new ArrayList<>();Tables tables = stmt.tables();for (Table table : tables) {Map<String, String> tableInfo = new HashMap<>();tableInfo.put("tableName", table.getName());tableInfo.put("remarks", table.getComment());tablelist.add(tableInfo);}return tablelist;}/*** 获取OPDS的字段colunmn的信息* @param stmt opds 已连接对象* @param tablename 表的名称* @return* @throws OdpsException*/public ArrayList<Map<String, String>> showTableFields(Odps stmt, String tablename) throws OdpsException {ArrayList<Map<String, String>> tableFieldlist = new ArrayList<>();Table t = stmt.tables().get(tablename);t.reload();TableSchema schema = t.getSchema();List<Column> columns = schema.getColumns();for (Column column : columns) {Map<String, String> fieldInfo = new HashMap<>();fieldInfo.put("columnName", column.getName());fieldInfo.put("remarks", column.getComment());tableFieldlist.add(fieldInfo);}return tableFieldlist;}/*** 获取表的数据预览* @param stmt* @param tablename* @throws OdpsException*/public void getTableData(Odps stmt, String tablename) throws OdpsException {String sql = "select * from " + tablename + " limit 5;";Instance i = SQLTask.run(stmt, sql);i.waitForSuccess();List<Record> records = SQLTask.getResult(i);for (Record r : records) {String fielddata1 = r.getString(1);String fielddata = r.getString("name");}}}
这篇关于ODPS的Java连接(2)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!