mysql 导出sql结果_导出SQL的运行结果

SQLTask配合Tunnel方式导出

SQLTask不能处理超过1万条数据,而Tunnel方式可以,两者可以互补,因此可以基于两者实现超过1万条数据的导出。

代码实现的示例如下。

private static final String accessId = "userAccessId";

private static final String accessKey = "userAccessKey";

private static final String endPoint = "http://service.cn-shanghai.maxcompute.aliyun.com/api";

private static final String project = "userProject";

private static final String sql = "userSQL";

private static final String table = "Tmp_" + UUID.randomUUID().toString().replace("-", "_");//用随机字符串作为临时表的名称。

private static final Odps odps = getOdps();

public static void main(String[] args) {

System.out.println(table);

runSql();

tunnel();

}

/*

* 下载SQLTask的结果。

* */

private static void tunnel() {

TableTunnel tunnel = new TableTunnel(odps);

try {

DownloadSession downloadSession = tunnel.createDownloadSession(

project, table);

System.out.println("Session Status is : "

+ downloadSession.getStatus().toString());

long count = downloadSession.getRecordCount();

System.out.println("RecordCount is: " + count);

RecordReader recordReader = downloadSession.openRecordReader(0,

count);

Record record;

while ((record = recordReader.read()) != null) {

consumeRecord(record, downloadSession.getSchema());

}

recordReader.close();

} catch (TunnelException e) {

e.printStackTrace();

} catch (IOException e1) {

e1.printStackTrace();

}

}

/*

* 保存数据。

* 数据量少时直接打印后拷贝也是可行的。实际场景可以用Java.io写到本地文件,或者写到远端存储上保存起来。

* */

private static void consumeRecord(Record record, TableSchema schema) {

System.out.println(record.getString("username")+","+record.getBigint("cnt"));

}

/*

* 运行SQL,把查询结果保存成临时表。

* 此处保存数据的生命周期为1天,即使删除步骤出了问题,也不会太浪费存储空间。

* */

private static void runSql() {

Instance i;

StringBuilder sb = new StringBuilder("Create Table ").append(table)

.append(" lifecycle 1 as ").append(sql);

try {

System.out.println(sb.toString());

i = SQLTask.run(getOdps(), sb.toString());

i.waitForSuccess();

} catch (OdpsException e) {

e.printStackTrace();

}

}

/*

* 初始化MaxCompute的连接信息。

* */

private static Odps getOdps() {

Account account = new AliyunAccount(accessId, accessKey);

Odps odps = new Odps(account);

odps.setEndpoint(endPoint);

odps.setDefaultProject(project);

return odps;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值