echarts从数据库获取数据制图

这篇博客介绍了如何利用ECharts结合数据库来动态绘制图表。首先讲解了如何使用DBUtil工具类连接MySQL获取数据,接着阐述了如何在servlet中处理这些数据。最后在echarts.jsp页面中引入echarts.js库,并展示了代码运行后的图表结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

echarts从数据库获取数据制图

首先是连接mysql的工具类(DBUtil ),

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
	 public static Connection getConn() {
	        //声明Connection对象
	        Connection con = null;
	        //驱动程序名
	        String driver = "com.mysql.jdbc.Driver";
	        //URL指向要访问的数据库名mydata
	        String url = "jdbc:mysql://localhost:3306/charge_index_compilation";
	        //MySQL配置时的用户名
	        String user = "root";
	        //MySQL配置时的密码
	        String password = "root";
	        //遍历查询结果集
	        try {
	            //加载驱动程序
	            Class.forName(driver);
	            //1.getConnection()方法,连接MySQL数据库!!
	            con = DriverManager.getConnection(url,user,password);
	            if(!con.isClosed())
	                System.out.println("Succeeded connecting to the Database!");
	        } catch(ClassNotFoundException e) {   
	            //数据库驱动类异常处理
	            System.out.println("Sorry,can`t find the Driver!");   
	            e.printStackTrace();   
	            } catch(SQLException e) {
	            //数据库连接失败异常处理
	            e.printStackTrace();  
	            }catch (Exception e) {
	            // TODO: handle exception
	            e.printStackTrace();
	        }finally{
	            System.out.println("数据库数据成功获取!!");
	        }
			return con;
	    }
	
}

获取数据库数据,以img1data类为例,

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class img1data {
	public static String Img1data() throws SQLException{		
		 Connection conn = null;
         Statement stmt=null;
         ResultSet rst = null;
         conn = DBUtil.getConn();
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");//日期格式
		String dates[]=new String[14];  //存放日期数组
		String resText="<datas>";    
		int i;
		for( i=0;i<14;i++){
			Date date=new Date();//取时间
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);	
			calendar.add(calendar.DAY_OF_MONTH,-i);//把日期往后增加一天.整数往后推,负数往前移动
			date=calendar.getTime(); //这个时间就是日期往后推一天的结果 
			dates[i] = dateformat.format(date);
			System.out.println("dates"+"["+i+"]"+dates[i]); 
		}		     
            stmt = conn.createStatement();
            String sql = "select composite_index_data.current_date,composite_index from composite_index_data where composite_index_data.current_date between'"+dates[13]+"'and '"+dates[0]+"'order by composite_index_data.current_date desc"  ;
            rst=stmt.executeQuery(sql);     
            while(rst.next()){
            	String img1_current_date=rst.getString("current_date").substring(0,10);
            	String composite_index=rst.getString("composite_index");
            	resText+="<data>"+"<img1_current_date>"+img1_current_date+"</img1_current_date>"+"<composite_index>"+composite_index+"</composite_index>"+"</data>";
            }
            resText+="</datas>";
   		  System.out.println(resText);
   		  return  resText;        	
	}
}		

servlet得到数据

package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import echarts.img1data;


public class servlet extends HttpServlet {
	public servlet() {
		super();
	}
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
	    try {
			out.write(img1data.Img1data());//向后台发送数据

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.flush();
		out.close();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
	public void init() throws ServletException {
		// Put your code here
	}
}

下面是echarts.jsp,首先要引入echarts.js,可以去echarts官网下载。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>myecharts</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	
  </head>
  <body onload="init()">
    <%-- <a href="javascript:void(0)" id="showdata">显示图形</a> --%>
    <div id="img1" style="width: 600px;height:400px;"></div>  
   <%-- <div id="img3" style="width: 600px;height:400px;"></div>  --%>
    <script> 
	   // alert("123");
	   // var link=document.getElementById("submit");
	    var url1="servlet/servlet";
	    function init(){   
	    var xhr1=new XMLHttpRequest();
	    //xhr.onloadend=function(){
	   xhr1.onreadystatechange=function(){
		// alert(xhr1.readyState+","+xhr1.status);
		    //if(xhr.status == 404){
		   //  throw new Error(url + ' replied 404');
		   // }else
		    if (xhr1.readyState==4&&xhr1.status==200){
		      	var xmlDoc1= xhr1.responseXML;
		      	//alert(xmlDoc1);
		    	var datas1 =xmlDoc1.getElementsByTagName("data"); 
		    //	alert(datas.length);  
		    	var img1_current_dates1=[];
		    	var composite_indexs1=[];
			    
			    for(var i=0;i<datas1.length;i++){
			      img1_current_dates1.push(datas1[i].childNodes[0].textContent);
			      composite_indexs1.push(datas1[i].childNodes[1].textContent);
			    }
		        // 基于准备好的dom,初始化echarts实例
		        var myChart1 = echarts.init(document.getElementById('img1'));
		        // 指定图表的配置项和数据
		        var option1 = {
		            title: {
		                text: '中国沿海煤炭运价指数'
		            },
		            tooltip: {},
		            legend: {
		                data:['日期']
		            },
		            xAxis: {
		                data: img1_current_dates1,
		                axisLabel:{
		                interval:0,
		                rotate:-30,
		                }
		                
		            },
		            yAxis: {},
		            series: [{
		                name: '指数',
		                type: 'line',
		                data: composite_indexs1
		            }]
		        };
		        // 使用刚指定的配置项和数据显示图表。
		        myChart1.setOption(option1);  
		        //alert("1000");
                    setTimeout(exportImage1, 3000);    
	                function exportImage1(){  
	                //alert("1000");
	                	//alert("exportImage()");
		                var a_base64 ="a="+myChart1.getDataURL();
			            // alert(a_base64);	
			              var xmlhttp;  
	                    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari  
	                        xmlhttp = new XMLHttpRequest();  
	                    } else { // code for IE6, IE5  
	                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  
	                    } 
	                    alert(xmlhttp); 
	                    xmlhttp.open("Post","<%=path%>/servlet/saveImage",true);  
	                    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");  
	                    xmlhttp.onreadystatechange = function() {  
	                 // alert(xmlhttp.readyState+","+xmlhttp.status); 
	                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {                  
	                   // alert("保存成功");	        
	                        }
	                    }
	                    xmlhttp.send(a_base64); 
	                    }  
                    }
                    } 	     	             
	    xhr1.open("get",url1,true);
	    xhr1.send();
	    }		    
    </script>
  </body>  
</html>

下面上图,为代码的运行结果。在这里插入图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值