Home forums Using CanvasJS Query Reply To: Query

#24375

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<%@ page import=”java.util.*,java.sql.*”%>
<%@ page import=”com.google.gson.Gson”%>
<%@ page import=”com.google.gson.JsonObject”%>
<%@ page import=”java.text.SimpleDateFormat”%>
<%@ page import=”java.util.Date”%>
<!– ========================================================================================================================= –>
<%
HashMap resultMap = new HashMap();
try{
Class.forName(“com.mysql.jdbc.Driver”);
Connection connection = DriverManager.getConnection(“database path”, “username”, “password”);
String table = (String)request.getAttribute(“FINAL_TABLE_NAME”);
//String sql = “SELECT * FROM ” + table + “;”;
String sql = “SELECT * FROM sampletime”;
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ArrayList data = new ArrayList();
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i < rsmd.getColumnCount(); i++) {
HashMap dataMap = new HashMap();
ArrayList list = new ArrayList();
String dataPoints = null;
Gson gson = new Gson();
rs.beforeFirst();
while (rs.next()) {
HashMap<String, Object> map = new HashMap();
String date = rs.getString(1);
SimpleDateFormat formater = new SimpleDateFormat(“yyyy-M-dd HH:mm”);
Date dt = formater.parse(date);
long l = (long) dt.getTime();
double d = (double) l;
map.put(“x”, d);
map.put(“y”, Double.parseDouble(rs.getString(i + 1)));
list.add(map);
dataPoints = gson.toJson(list);
}
dataMap.put(“type”, “line”);
dataMap.put(“xValueType”, “dateTime”);
dataMap.put(“dataPoints”, “<%out.print(” + dataPoints + “);%” + “>”);
data.add(dataMap);
}
resultMap.put(“data”, data);
out.println(resultMap.get(“data”));
}catch(SQLException e){
e.printStackTrace();
out.println(“<div style=’width: 50%; margin-left: auto; margin-right: auto; margin-top: 200px;’>Could not connect to the database. Please check if you have mySQL Connector installed on the machine – if not, try installing the same.</div>”);
}
%>
<!– ***************************************************************************************************************** –>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<script type=”text/javascript”>
window.onload = function() {
<%if(resultMap != null)
{%>
var chart = new CanvasJS.Chart(“chartContainer”, {
animationEnabled : true,
exportEnabled : true,
title : {
text : “JSP Column Chart from Database”
},
data : <%out.println(resultMap.get(“data”));%>

});

chart.render();
<%}%>

}
</script>
</head>
<body>
<div id=”chartContainer” style=”height: 370px; width: 100%;”></div>

</body>
</html>