以共享单车日志为例,共享单车日志内容包括用户年龄、性别、电量使用量、车辆ID、操作延时、纬度、锁类型、经度、操作类型、操作结果和开锁方式。数据保存在名为project:trip_demo的Project下,名为Logstore:ebike的Logstore中。Project所在地域是cn-hangzhou。
注意
使用Java的JDBC、Python的MySQLdb等库在程序中访问日志服务时,服务入口必须使用日志服务的经典网络或VPC网络访问域名,否则会出现连接超时报错
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure,Caused
by: java.net.ConnectException: Connection timed out: connect
。
* Created by mayunlei on 2017/6/19.
import com.mysql.jdbc.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.Statement;
* Created by mayunlei on 2017/6/15.
public class jdbc {
public static void main(String args[]){
final String endpoint = "trip-demo.cn-hangzhou-intranet.log.aliyuncs.com"; //包括Project名称和日志服务经典网络或VPC网络访问域名,请根据实际情况替换。更多信息,请参见
服务入口
。
final String port = "10005"; //通过JDBC访问时,默认使用10005端口。
final String project = "trip-demo"; //Project名称。
final String logstore = "ebike"; //Logstore名称。
final String accessKeyId = ""; //阿里云访问密钥AccessKey ID。更多信息,请参见
访问密钥
。
final String accessKey = ""; //阿里云访问密钥AccessKey Secret。
Connection conn = null;
Statement stmt = null;
try {
//步骤1 :加载JDBC驱动。
Class.forName("com.mysql.jdbc.Driver");
//步骤2 :创建一个链接。
conn = DriverManager.getConnection("jdbc:mysql://"+endpoint+":"+port+"/"+project,accessKeyId,accessKey);
//步骤3 :创建statement。
stmt = conn.createStatement();
//步骤4 :定义查询语句,查询2017年10月11日全天日志中满足条件op = "unlock"的日志条数。
String sql = "select count(1) as pv,avg(latency) as avg_latency from "+logstore+" " +
"where __date__ >= '2017-10-11 00:00:00' " +
" and __date__ < '2017-10-12 00:00:00'" +
" and op ='unlock'";
//步骤5 :执行查询条件。
ResultSet rs = stmt.executeQuery(sql);
//步骤6 :提取查询结果。
while(rs.next()){
//Retrieve by column name
System.out.print("pv:");
//获取结果中的pv。
System.out.print(rs.getLong("pv"));
System.out.print(" ; avg_latency:");
//获取结果中的avg_latency。
System.out.println(rs.getDouble("avg_latency"));
System.out.println();
rs.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();