Accessing MaxCompute Lightning with Java and Python for App Development

Join us at the Alibaba Cloud ACtivate Online Conference on March 5–6 to challenge assumptions, exchange ideas, and explore what is possible through digital transformation.

MaxCompute Lightning provides interactive query services for Alibaba Cloud MaxCompute, and supports easy connection to MaxCompute projects based on the PostgreSQL protocol and syntax. This service allows you to quickly query and analyze MaxCompute project data using standard SQL and commonly used tools.

Many developers want to use Lightning’s features to develop data applications. This article will introduce examples showing how Java and Python connect to Lightning for application development (the endpoint and user authentication information of the region where your project is located needs to be replaced when referring to these examples in the article).

Using JDBC to Access Lightning with Java


import java.sql. *;public class Main {    private static Connection connection;    public static void main(String[] args) throws SQLException {        String url = "jdbc:postgresql:// 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 ( {
System.out.println(rs.getString(1)+ "\t");
System.out.println("End Lightning query");
} catch (SQLException e) {
public static Connection getCon(String lightningsHost, String lightningUser, String lightningPwd) {
try {
if (connection == null || connection.isClosed()) {
try {
connection = DriverManager.getConnection(lightningsHost, lightningUser, lightningPwd);
} catch (Exception ex) {
} catch (Exception ex) {
return connection;

Using Druid to Access Lightning with Java

Pom dependency:


Spring configuration:

<bean id="LightningDataSource" class="" init-method="init" destroy-method="close">
<property name="url" value="jdbc:postgresql:// prepareThreshold=0&sslmode=require"/> <! -- Replace it with the endpoint of the region where your project is located—>
<property name="username" value="Access Key ID of the user"/>
<property name="password" value="Access Key Secret of the user"/>
<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" /> <!— The Lightning service limits the number of connections per project to 20, so do not set this value too high, and instead configure it as needed, otherwise, query_wait_timeout errors may occur -->

<! -- The following two configurations are used to detect the validity of the connection and fix the occasional "create connection holder error" error. -->
<property name="testWhileIdle" value="true" />
<property name="validationQuery" value="SELECT 1" />
<bean class="">
<property name="druidDataSource" ref="LightningDataSource"/>

Code access:

public class LightningProvider {    DruidDataSource druidDataSource;
* execute SQL
* @param sql
* @return
* @throws Exception
public void execute(String sql) throws SQLException {
DruidPooledConnection connection = null ;
Statement st = null;
connection = druidDataSource.getConnection();
st = connection.createStatement();
ResultSet resultSet = st.executeQuery(sql);
//The code for resolving and processing the return value
//Processing by row. The data of each row is put into a map
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
List<LinkedHashMap> rows = Lists.newArrayList();
LinkedHashMap map = Maps.newLinkedHashMap();
for(int i=1;i<=columnCount;i++){
String label = resultSet.getMetaData().getColumnLabel(i);
}catch (Exception e){
}finally {
try {
if(st! =null) {
} catch (SQLException e) {
try {
if(connection! =null) {
} catch (SQLException e) {

Using pyscopg2 to Access Lightning with Python


#! /usr/bin/env python
# coding=utf-8
import psycopg2
import sys
def query_lightning(lightning_conf, sql):
"""Query data through Lightning by sql
lightning_conf: a map contains settings of 'dbname', 'user', 'password', 'host', 'port'
sql: query submit to Lightning
result: the query result in format of list of rows
result = None
conn = None
conn_str = None
conn_str = ("dbname={dbname} "
"user={user} "
"password={password} "
"host={host} "
except Exception, e:
print >> sys.stderr, ("Invalid Lightning' configuration "
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
# get result
result = cur.fetchall()
except Exception, e:
print >> sys.stderr, ("Failed to query data through "
"Lightning: {}".format(e))
if conn:
return resultif __name__ == "__main__":
# step1. setup configuration
lightning_conf = {
"dbname": "your_project_name",
"user": "<your_maxcompute_access_id>",
"password": "<your_maxcompute_access_key>",
"host": "", #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])

Using ODBC to Access Lightning with Python

You need to install and configure an ODBC driver on your computer to use this method.

Sample code:

import pyodbc
conn_str = (
"DRIVER={PostgreSQL Unicode};"
";" #your region lightning endpoint
conn = pyodbc.connect(conn_str)
crsr = conn.execute("SELECT * from test")
row = crsr.fetchone()

Lightning provides a PostgreSQL-compatible interface, so you can develop Lightning applications just like PostgreSQL applications.

Learn more about Alibaba Cloud MaxCompute at


Follow me to keep abreast with the latest technology news, industry insights, and developer trends.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store