MaxCompute Lightning是MaxCompute产品的交互式查询服务,支持以PostgreSQL协议及语法连接访问Maxcompute项目,让您使用熟悉的工具以标准 SQL查询分析MaxCompute项目中的数据,快速获取查询结果。
很多开发者希望利用Lightning的特性来开发数据应用,本文将结合示例来介绍Java和Python如何连接访问Lightning进行应用开发(参考时需要替换为您项目所在region的Endpoint及用户认证信息)。
一、Java使用JDBC访问Lightning
示例如下:

import java.sql.*;

public class Main {

    private static Connection connection;

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

        String url = "jdbc:postgresql://lightning.cn-shanghai.maxcompute.aliyun.com:443/your_project_name?prepareThreshold=0&sslmode=require";
String accessId = "<your_maxcompute_access_id>";
String accessKey = "<your_maxcompute_access_key>";
String sql = "select * from dual"; try {
Connection conn = getCon(url, accessId, accessKey);
Statement st = conn.createStatement();
System.out.println("Send Lightning query");
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1)+ "\t");
}
System.out.println("End Lightning query");
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} public static Connection getCon(String lightningsHost, String lightningUser, String lightningPwd) {
try {
if (connection == null || connection.isClosed()) {
try {
Class.forName("org.postgresql.Driver").newInstance();
DriverManager.setLoginTimeout(1);
connection = DriverManager.getConnection(lightningsHost, lightningUser, lightningPwd);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return connection;
}
}

二、Java使用druid访问Lightning
1.pom依赖

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.23</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1101-jdbc4</version>
</dependency>

2.spring配置

    <bean id="LightningDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="jdbc:postgresql://lightning.cn-shanghai.maxcompute.aliyun.com:443/project_name?prepareThreshold=0&sslmode=require”/> <!--替换成自己project所在region的Endpoint—>
<property name="username" value=“访问用户的Access Key ID"/>
<property name="password" value="访问用户的Access Key Secret"/>
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="dbType" value="postgresql"/>
<property name="initialSize" value="1" />  
<property name="minIdle" value="1" />
<property name="maxActive" value="5" />  <!—Lightning服务每个project的连接数限制20,所以不要配置过大,按需配置,否则容易出现query_wait_timeout错误 --> <!--以下两个配置,检测连接有效性,修复偶尔出现create connection holder error错误 -->
  <property name="testWhileIdle" value="true" />
<property name="validationQuery" value="SELECT 1" />
</bean> <bean class="com.xxx.xxx.LightningProvider">
<property name="druidDataSource" ref="LightningDataSource"/>
</bean>

3.代码访问

public class LightningProvider {

    DruidDataSource druidDataSource;
/**
* 执行sql
* @param sql
* @return
* @throws Exception
*/
public void execute(String sql) throws SQLException {
DruidPooledConnection connection = null ;
       Statement st = null;
try{
connection = druidDataSource.getConnection();
st = connection.createStatement(); ResultSet resultSet = st.executeQuery(sql);
//对返回值的解析和处理的代码
//按行处理,每行的数据放到一个map中
ResultSetMetaData metaData = resultSet.getMetaData();
           int columnCount = metaData.getColumnCount();
    List<LinkedHashMap> rows = Lists.newArrayList();
    while(resultSet.next()){
LinkedHashMap map = Maps.newLinkedHashMap();
for(int i=1;i<=columnCount;i++){
String label = resultSet.getMetaData().getColumnLabel(i);
map.put(label,resultSet.getString(i));
}
rows.add(map);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(st!=null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
} try {
if(connection!=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

三、Python使用pyscopg2访问Lightning
示例如下:

#!/usr/bin/env python
# coding=utf-8 import psycopg2
import sys def query_lightning(lightning_conf, sql):
"""Query data through Lightning by sql Args:
lightning_conf: a map contains settings of 'dbname', 'user', 'password', 'host', 'port'
sql: query submit to Lightning Returns:
result: the query result in format of list of rows
"""
result = None
conn = None
conn_str = None
try:
conn_str = ("dbname={dbname} "
"user={user} "
"password={password} "
"host={host} "
"port={port}").format(**lightning_conf)
except Exception, e:
print >> sys.stderr, ("Invalid Lightning' configuration "
"{}".format(e))
sys.exit(1) try:
conn = psycopg2.connect(conn_str)
conn.set_session(autocommit=True) # This will disable transaction
# started with keyword BEGIN,
# which is currently not
# supported by Lightning’ public service cur = conn.cursor()
# execute Lightning' query
cur.execute(sql)
# get result
result = cur.fetchall()
except Exception, e:
print >> sys.stderr, ("Failed to query data through "
"Lightning: {}".format(e))
finally:
if conn:
conn.close() return result if __name__ == "__main__":
# step1. setup configuration
lightning_conf = {
"dbname": “your_project_name”,
"user": "<your_maxcompute_access_id>",
"password": "<your_maxcompute_access_key>",
"host": "lightning.cn-shanghai.maxcompute.aliyun.com", #your region lightning endpoint
"port": 443
} # step2. issue a query
result = query_lightning(lightning_conf, "select * from test”)
# step3. print result
if result:
for i in xrange(0, len(result)):
print "Got %d row from Lightning:%s" % (i + 1, result[i])

四、Python使用ODBC访问Lightning
您需要现在电脑上安装并和配置odbc驱动。代码示例如下:

import pyodbc
conn_str = (
"DRIVER={PostgreSQL Unicode};"
"DATABASE=your_project_name;"
"UID=your_maxcompute_access_id;"
"PWD=your_maxcompute_access_key;"
"SERVER=lightning.cn-shanghai.maxcompute.aliyun.com;" #your region lightning endpoint
"PORT=443;"
)
conn = pyodbc.connect(conn_str)
crsr = conn.execute("SELECT * from test”)
row = crsr.fetchone()
print(row)
crsr.close()
conn.close()

由于Lightning提供了PostgreSQL兼容的接口,您可以像开发PostgreSQL的应用一样开发Lightning应用程序。

MaxCompute产品官方地址:https://www.aliyun.com/product/odps

使用应用程序(Java/Python)访问MaxCompute Lightning进行数据开发的更多相关文章

  1. 使用python访问网络上的数据

    这两天看完了Course上面的: 使用 Python 访问网络数据 https://www.coursera.org/learn/python-network-data/ 写了一些作业,完成了一些作业 ...

  2. Java后端开发工程师是否该转大数据开发?

    撰写我对java后端开发工程师选择方向的想法,写给在java后端选择转方向的人 背景 看到一些java开发工程师,对java后端薪酬太悲观了.认为换去大数据领域就会高工资.觉得java后端没有前途.我 ...

  3. 杭州某知名xxxx公司急招大量java以及大数据开发工程师

    因公司战略以及业务拓展,收大量java攻城狮以及大数据开发攻城狮. 职位信息: java攻城狮: https://job.cnblogs.com/offer/56032 大数据开发攻城狮: https ...

  4. Spring MVC 程序首页的设置 - 一号门-程序员的工作,程序员的生活(java,python,delphi实战)

    body { font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI ...

  5. Java程序通过代理访问网络

    问题背景 最近工作上有开发爬虫的任务,对目标网站数据进行抓取,由于大部分网站都在国外,无法直接访问,需要通过代理才能登录.爬虫部署的服务器在香港,所以爬虫部署到服务器后,是可以访问目标网站的,但本地开 ...

  6. 一起学Hadoop——使用IDEA编写第一个MapReduce程序(Java和Python)

    上一篇我们学习了MapReduce的原理,今天我们使用代码来加深对MapReduce原理的理解. wordcount是Hadoop入门的经典例子,我们也不能免俗,也使用这个例子作为学习Hadoop的第 ...

  7. 前端,Java,产品经理,微信小程序,Python等资源合集大放送

    为了感恩大家长久以来的关注和支持,小编准备了一些福利,整理了包含前端,Java,产品经理,微信小程序,Python,网站源码,Android应用视频教程,微信公众平台开发教程及材料等资源合集大放送. ...

  8. 寻找下一个结点 牛客网 程序员面试金典 C++ java Python

    寻找下一个结点 牛客网 程序员面试金典 C++ java Python 题目描述 请设计一个算法,寻找二叉树中指定结点的下一个结点(即中序遍历的后继). 给定树的根结点指针TreeNode* root ...

  9. 碰撞的蚂蚁 牛客网 程序员面试金典 C++ Java Python

    碰撞的蚂蚁 牛客网 程序员面试金典 C++ Java Python 题目描述 在n个顶点的多边形上有n只蚂蚁,这些蚂蚁同时开始沿着多边形的边爬行,请求出这些蚂蚁相撞的概率.(这里的相撞是指存在任意两只 ...

随机推荐

  1. centos7.4安装高可用(haproxy+keepalived实现)kubernetes1.6.0集群(开启TLS认证)

    目录 目录 前言 集群详情 环境说明 安装前准备 提醒 一.创建TLS证书和秘钥 安装CFSSL 创建 CA (Certificate Authority) 创建 CA 配置文件 创建 CA 证书签名 ...

  2. python之tkinter学习目录

    前言 下面的目录结构,采用的学习视频资料是网易云课堂中[莫凡]老师的,在目录的最下面的地方给出了对应的链接! 学习是逐渐积累起来的,代码也是!下面的每一篇中的对应代码,都秉承着这样的一个理念:代码是成 ...

  3. LED 发光二极管压降

    常用发光二极管的压降 1. 直插超亮发光二极管压降 主要有三种颜色,然而三种发光二极管的压降都不相同,具体压降参考值如下: 红色发光二极管的压降为2.0--2.2V  黄色发光二极管的压降为1.8—2 ...

  4. CodeForces 1152D Neko and Aki's Prank

    说明 Catalan(i) 表示卡特兰数的第 i 项. 题目链接:http://codeforces.com/problemset/problem/1152/C 题目大意 有 n 个左括号和 n 个右 ...

  5. Python匹马行天下之python之父

    龟叔和他的python 经过了漫长的旅程,终于要看到主角Python了.Python是现在非常非常流行的编程语言,在我们能看到的大部分编程语言排行榜中,Python都能在前三甲中拥有一席之地 ,并且发 ...

  6. USACO2005 City Skyline /// oj23401

    题目大意: Input * Line 1: Two space separated integers: N and W * Lines 2..N+1: Two space separated inte ...

  7. SVG动画制作工具 , 从此抛弃臃肿的gif

    VG简介 只要是程序员的你,你不得不知道svg图片,它可以无限任意放大拉伸都不会损失画质,就像系统字体一样可以无限矢量放大,svg更高级是可以用来制作矢量动画,现在各大浏览器和系统基本对svg已经支持 ...

  8. lock tables和unlock tables

    1.lock tables table1 read,table2 read,table3 read igoodful@a8-apple-iphone-db00.wh(glc) > show ta ...

  9. leetcode-50-pow()

    题目描述: 方法一: class Solution: def myPow(self, x: float, n: int) -> float: if n<0: x = 1/x return ...

  10. CSS——元素的显示与隐藏

    元素的显示与隐藏 在CSS中有三个显示和隐藏的单词比较常见,我们要区分开,他们分别是 display visibility 和 overflow. 他们的主要目的是让一个元素在页面中消失,但是不在文档 ...