Chart.js与SQLite集成实战指南从数据存储到动态图表的完整解决方案

引言
在现代Web应用中,数据可视化是展示信息和洞察的关键组成部分。Chart.js作为一个轻量级、灵活的JavaScript图表库,能够创建各种类型的交互式图表。而SQLite作为一个轻量级的嵌入式数据库,非常适合在客户端或小型服务器应用中存储结构化数据。将这两者结合,可以构建出从数据存储到动态图表展示的完整解决方案。
本文将详细介绍如何将Chart.js与SQLite集成,涵盖从数据库设计、数据操作到前端图表渲染的全过程。我们将通过一个完整的示例项目来演示如何实现动态数据图表,包括实时数据更新、数据过滤和图表交互等功能。
1. 技术栈概述
1.1 Chart.js简介
Chart.js是一个基于HTML5 Canvas的开源图表库,支持多种图表类型:
折线图(Line)
柱状图(Bar)
饼图/环形图(Pie/Doughnut)
面积图(Area)
散点图(Scatter)
雷达图(Radar)
极坐标图(Polar Area)
特点:
轻量级(压缩后约60KB)
响应式设计
支持动画效果
可自定义样式
良好的浏览器兼容性
1.2 SQLite简介
SQLite是一个C语言编写的轻量级关系型数据库,具有以下特点:
零配置,无需服务器
单个数据库文件存储所有数据
跨平台,支持多种操作系统
事务支持,符合ACID特性
支持标准SQL语法
1.3 集成架构
我们将采用以下架构:
前端(浏览器) → 后端(Node.js/Express) → SQLite数据库
↓
Chart.js图表
2. 环境准备与项目设置
2.1 安装Node.js和npm
首先确保已安装Node.js(建议版本14.x或更高)和npm。
2.2 创建项目目录
mkdir chartjs-sqlite-demo
cd chartjs-sqlite-demo
npm init -y
2.3 安装依赖
# 后端依赖
npm install express sqlite3 cors

# 前端依赖(我们将使用CDN引入Chart.js)
# 如果需要构建工具,可以安装webpack等
2.4 项目结构
chartjs-sqlite-demo/
├── server.js # 后端服务器
├── database/
│ └── db.js # 数据库操作模块
├── public/
│ ├── index.html # 前端页面
│ ├── css/
│ │ └── style.css # 样式文件
│ └── js/
│ └── app.js # 前端逻辑
├── package.json
└── README.md
3. SQLite数据库设计与实现
3.1 数据库设计
我们创建一个销售数据示例,包含以下表结构:
— 销售记录表
CREATE TABLE IF NOT EXISTS sales (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_name TEXT NOT NULL,
quantity INTEGER NOT NULL,
price REAL NOT NULL,
sale_date DATE NOT NULL,
category TEXT
);

— 产品类别表
CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
description TEXT
);

— 插入示例数据
INSERT INTO categories (name, description) VALUES
(‘电子产品’, ‘各类电子设备’),
(‘服装’, ‘服装鞋帽’),
(‘食品’, ‘食品饮料’);

INSERT INTO sales (product_name, quantity, price, sale_date, category) VALUES
(‘iPhone 14’, 2, 799.99, ‘2024-01-15’, ‘电子产品’),
(‘MacBook Pro’, 1, 1999.99, ‘2024-01-16’, ‘电子产品’),
(‘牛仔裤’, 3, 49.99, ‘2024-01-17’, ‘服装’),
(‘T恤’, 5, 19.99, ‘2024-01-18’, ‘服装’),
(‘苹果’, 10, 2.99, ‘2024-01-19’, ‘食品’),
(‘牛奶’, 4, 3.49, ‘2024-01-20’, ‘食品’),
(‘iPhone 14 Pro’, 1, 999.99, ‘2024-01-21’, ‘电子产品’),
(‘运动鞋’, 2, 89.99, ‘2024-01-22’, ‘服装’),
(‘香蕉’, 8, 1.99, ‘2024-01-23’, ‘食品’),
(‘iPad’, 1, 499.99, ‘2024-01-24’, ‘电子产品’);
3.2 数据库操作模块
创建
database/db.js
文件:
const sqlite3 = require(‘sqlite3’).verbose();
const path = require(‘path’);

// 数据库文件路径
const dbPath = path.join(__dirname, ‘sales.db’);

// 创建数据库连接
const db = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error(‘数据库连接失败:’, err.message);
} else {
console.log(‘成功连接到SQLite数据库’);
initializeDatabase();
}
});

// 初始化数据库
function initializeDatabase() {
// 创建销售记录表
db.run(`CREATE TABLE IF NOT EXISTS sales (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_name TEXT NOT NULL,
quantity INTEGER NOT NULL,
price REAL NOT NULL,
sale_date DATE NOT NULL,
category TEXT
)`);

// 创建类别表
db.run(`CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
description TEXT
)`);

// 检查是否已有数据,如果没有则插入示例数据
db.get(“SELECT COUNT(*) as count FROM sales”, (err, row) => {
if (err) {
console.error(‘查询数据失败:’, err.message);
return;
}

if (row.count === 0) {
console.log(‘插入示例数据…’);
insertSampleData();
}
});
}

// 插入示例数据
function insertSampleData() {
const categories = [
[‘电子产品’, ‘各类电子设备’],
[‘服装’, ‘服装鞋帽’],
[‘食品’, ‘食品饮料’]
];

const sales = [
[‘iPhone 14’, 2, 799.99, ‘2024-01-15’, ‘电子产品’],
[‘MacBook Pro’, 1, 1999.99, ‘2024-01-16’, ‘电子产品’],
[‘牛仔裤’, 3, 49.99, ‘2024-01-17’, ‘服装’],
[‘T恤’, 5, 19.99, ‘2024-01-18’, ‘服装’],
[‘苹果’, 10, 2.99, ‘2024-01-19’, ‘食品’],
[‘牛奶’, 4, 3.49, ‘2024-01-20’, ‘食品’],
[‘iPhone 14 Pro’, 1, 999.99, ‘2024-01-21’, ‘电子产品’],
[‘运动鞋’, 2, 89.99, ‘2024-01-22’, ‘服装’],
[‘香蕉’, 8, 1.99, ‘2024-01-23’, ‘食品’],
[‘iPad’, 1, 499.99, ‘2024-01-24’, ‘电子产品’]
];

// 插入类别
const categoryStmt = db.prepare(“INSERT INTO categories (name, description) VALUES (?, ?)”);
categories.forEach(cat => {
categoryStmt.run(cat, (err) => {
if (err) console.error(‘插入类别失败:’, err.message);
});
});
categoryStmt.finalize();

// 插入销售数据
const salesStmt = db.prepare(“INSERT INTO sales (product_name, quantity, price, sale_date, category) VALUES (?, ?, ?, ?, ?)”);
sales.forEach(sale => {
salesStmt.run(sale, (err) => {
if (err) console.error(‘插入销售数据失败:’, err.message);
});
});
salesStmt.finalize();
}

// 数据库操作函数
const dbOperations = {
// 获取所有销售数据
getAllSales: function(callback) {
const sql = `SELECT s.*, c.name as category_name
FROM sales s
LEFT JOIN categories c ON s.category = c.name
ORDER BY s.sale_date DESC`;
db.all(sql, [], (err, rows) => {
if (err) {
callback(err, null);
} else {
callback(null, rows);
}
});
},

// 按类别获取销售数据
getSalesByCategory: function(category, callback) {
const sql = `SELECT s.*, c.name as category_name
FROM sales s
LEFT JOIN categories c ON s.category = c.name
WHERE s.category = ?
ORDER BY s.sale_date DESC`;
db.all(sql, [category], (err, rows) => {
if (err) {
callback(err, null);
} else {
callback(null, rows);
}
});
},

// 按日期范围获取销售数据
getSalesByDateRange: function(startDate, endDate, callback) {
const sql = `SELECT s.*, c.name as category_name
FROM sales s
LEFT JOIN categories c ON s.category = c.name
WHERE s.sale_date BETWEEN ? AND ?
ORDER BY s.sale_date DESC`;
db.all(sql, [startDate, endDate], (err, rows) => {
if (err) {
callback(err, null);
} else {
callback(null, rows);
}
});
},

// 获取按类别汇总的销售数据(用于图表)
getSalesSummaryByCategory: function(callback) {
const sql = `SELECT
category,
SUM(quantity) as total_quantity,
SUM(quantity * price) as total_revenue,
COUNT(*) as sale_count
FROM sales
GROUP BY category
ORDER BY total_revenue DESC`;
db.all(sql, [], (err, rows) => {
if (err) {
callback(err, null);
} else {
callback(null, rows);
}
});
},

// 获取按日期汇总的销售数据(用于时间序列图表)
getSalesSummaryByDate: function(callback) {
const sql = `SELECT
sale_date,
SUM(quantity) as total_quantity,
SUM(quantity * price) as total_revenue,
COUNT(*) as sale_count
FROM sales
GROUP BY sale_date
ORDER BY sale_date ASC`;
db.all(sql, [], (err, rows) => {
if (err) {
callback(err, null);
} else {
callback(null, rows);
}
});
},

// 添加新销售记录
addSale: function(product_name, quantity, price, sale_date, category, callback) {
const sql = `INSERT INTO sales (product_name, quantity, price, sale_date, category)
VALUES (?, ?, ?, ?, ?)`;
db.run(sql, [product_name, quantity, price, sale_date, category], function(err) {
if (err) {
callback(err, null);
} else {
callback(null, { id: this.lastID });
}
});
},

// 添加新类别
addCategory: function(name, description, callback) {
const sql = `INSERT INTO categories (name, description) VALUES (?, ?)`;
db.run(sql, [name, description], function(err) {
if (err) {
callback(err, null);
} else {
callback(null, { id: this.lastID });
}
});
},

// 获取所有类别
getAllCategories: function(callback) {
db.all(“SELECT * FROM categories ORDER BY name”, [], (err, rows) => {
if (err) {
callback(err, null);
} else {
callback(null, rows);
}
});
}
};

// 关闭数据库连接
process.on(‘SIGINT’, () => {
db.close((err) => {
if (err) {
console.error(‘关闭数据库时出错:’, err.message);
} else {
console.log(‘数据库连接已关闭’);
}
process.exit(0);
});
});

module.exports = dbOperations;
4. 后端服务器实现
4.1 创建Express服务器
创建
server.js
文件:
const express = require(‘express’);
const cors = require(‘cors’);
const path = require(‘path’);
const db = require(‘./database/db’);

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(‘public’));

// API路由

// 1. 获取所有销售数据
app.get(‘/api/sales’, (req, res) => {
db.getAllSales((err, data) => {
if (err) {
res.status(500).json({ error: err.message });
} else {
res.json(data);
}
});
});

// 2. 按类别获取销售数据
app.get(‘/api/sales/category/:category’, (req, res) => {
const category = req.params.category;
db.getSalesByCategory(category, (err, data) => {
if (err) {
res.status(500).json({ error: err.message });
} else {
res.json(data);
}
});
});

// 3. 按日期范围获取销售数据
app.get(‘/api/sales/date-range’, (req, res) => {
const { startDate, endDate } = req.query;
if (!startDate || !endDate) {
return res.status(400).json({ error: ‘需要提供startDate和endDate参数’ });
}

db.getSalesByDateRange(startDate, endDate, (err, data) => {
if (err) {
res.status(500).json({ error: err.message });
} else {
res.json(data);
}
});
});

// 4. 获取按类别汇总的销售数据(用于图表)
app.get(‘/api/sales/summary/category’, (req, res) => {
db.getSalesSummaryByCategory((err, data) => {
if (err) {
res.status(500).json({ error: err.message });
} else {
res.json(data);
}
});
});

// 5. 获取按日期汇总的销售数据(用于时间序列图表)
app.get(‘/api/sales/summary/date’, (req, res) => {
db.getSalesSummaryByDate((err, data) => {
if (err) {
res.status(500).json({ error: err.message });
} else {
res.json(data);
}
});
});

// 6. 添加新销售记录
app.post(‘/api/sales’, (req, res) => {
const { product_name, quantity, price, sale_date, category } = req.body;

// 验证输入
if (!product_name || !quantity || !price || !sale_date) {
return res.status(400).json({ error: ‘缺少必要字段’ });
}

db.addSale(product_name, quantity, price, sale_date, category, (err, result) => {
if (err) {
res.status(500).json({ error: err.message });
} else {
res.json({ message: ‘销售记录添加成功’, id: result.id });
}
});
});

// 7. 获取所有类别
app.get(‘/api/categories’, (req, res) => {
db.getAllCategories((err, data) => {
if (err) {
res.status(500).json({ error: err.message });
} else {
res.json(data);
}
});
});

// 8. 添加新类别
app.post(‘/api/categories’, (req, res) => {
const { name, description } = req.body;

if (!name) {
return res.status(400).json({ error: ‘类别名称不能为空’ });
}

db.addCategory(name, description, (err, result) => {
if (err) {
res.status(500).json({ error: err.message });
} else {
res.json({ message: ‘类别添加成功’, id: result.id });
}
});
});

// 9. 前端页面路由
app.get(‘/’, (req, res) => {
res.sendFile(path.join(__dirname, ‘public’, ‘index.html’));
});

// 启动服务器
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});
5. 前端实现
5.1 HTML页面结构
创建
public/index.html
文件:





Chart.js与SQLite集成示例


销售数据可视化仪表板

使用Chart.js与SQLite集成的动态图表示例





至


原始数据


ID 产品名称 数量 单价 总价 销售日期 类别

添加新销售记录










5.2 CSS样式
创建
public/css/style.css
文件:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-family: ‘Segoe UI’, Tahoma, Geneva, Verdana, sans-serif;
background-color: #f5f5f5;
color: #333;
line-height: 1.6;
}

.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}

header {
text-align: center;
margin-bottom: 30px;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

header h1 {
font-size: 2.5rem;
margin-bottom: 10px;
}

header p {
font-size: 1.1rem;
opacity: 0.9;
}

.controls {
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
display: flex;
flex-wrap: wrap;
gap: 15px;
align-items: center;
}

.control-group {
display: flex;
flex-direction: column;
gap: 5px;
}

.control-group label {
font-weight: 600;
font-size: 0.9rem;
color: #555;
}

.control-group select,
.control-group input {
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 0.95rem;
background: white;
}

.control-group input[type=”date”] {
min-width: 150px;
}

button {
padding: 10px 20px;
background: #667eea;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-weight: 600;
transition: background 0.3s;
}

button:hover {
background: #5a67d8;
}

.chart-container {
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
min-height: 400px;
}

.data-table-container {
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
overflow-x: auto;
}

.data-table-container h3 {
margin-bottom: 15px;
color: #667eea;
}

table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}

thead {
background: #f8f9fa;
}

th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #e9ecef;
}

th {
font-weight: 600;
color: #495057;
}

tbody tr:hover {
background: #f8f9fa;
}

.add-data-container {
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.add-data-container h3 {
margin-bottom: 15px;
color: #667eea;
}

#addSaleForm {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
}

.form-group {
display: flex;
flex-direction: column;
gap: 5px;
}

.form-group label {
font-weight: 600;
font-size: 0.9rem;
color: #555;
}

.form-group input,
.form-group select {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 0.95rem;
}

#addSaleForm button {
grid-column: 1 / -1;
margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
.controls {
flex-direction: column;
align-items: stretch;
}

.control-group {
width: 100%;
}

#addSaleForm {
grid-template-columns: 1fr;
}

header h1 {
font-size: 1.8rem;
}
}

/* 加载动画 */
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-left: 10px;
}

@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}

/* 错误提示 */
.error-message {
color: #dc3545;
background: #f8d7da;
padding: 10px;
border-radius: 5px;
margin: 10px 0;
border-left: 4px solid #dc3545;
}

/* 成功提示 */
.success-message {
color: #155724;
background: #d4edda;
padding: 10px;
border-radius: 5px;
margin: 10px 0;
border-left: 4px solid #28a745;
}
5.3 前端JavaScript逻辑
创建
public/js/app.js
文件:
// 全局变量
let mainChart = null;
let currentData = [];

// DOM元素
const chartTypeSelect = document.getElementById(‘chartType’);
const dataViewSelect = document.getElementById(‘dataView’);
const startDateInput = document.getElementById(‘startDate’);
const endDateInput = document.getElementById(‘endDate’);
const updateChartBtn = document.getElementById(‘updateChart’);
const refreshDataBtn = document.getElementById(‘refreshData’);
const dataTableBody = document.querySelector(‘#dataTable tbody’);
const categorySelect = document.getElementById(‘category’);
const addSaleForm = document.getElementById(‘addSaleForm’);

// 初始化
document.addEventListener(‘DOMContentLoaded’, function() {
loadCategories();
loadChartData();
setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
updateChartBtn.addEventListener(‘click’, loadChartData);
refreshDataBtn.addEventListener(‘click’, loadChartData);
addSaleForm.addEventListener(‘submit’, handleAddSale);

// 自动更新图表当选择改变时
chartTypeSelect.addEventListener(‘change’, updateChart);
dataViewSelect.addEventListener(‘change’, loadChartData);
startDateInput.addEventListener(‘change’, loadChartData);
endDateInput.addEventListener(‘change’, loadChartData);
}

// 加载类别选项
async function loadCategories() {
try {
const response = await fetch(‘/api/categories’);
const categories = await response.json();

// 清空现有选项(除了第一个)
while (categorySelect.options.length > 1) {
categorySelect.remove(1);
}

// 添加类别选项
categories.forEach(category => {
const option = document.createElement(‘option’);
option.value = category.name;
option.textContent = category.name;
categorySelect.appendChild(option);
});
} catch (error) {
console.error(‘加载类别失败:’, error);
showMessage(‘加载类别失败,请检查服务器连接’, ‘error’);
}
}

// 加载图表数据
async function loadChartData() {
const dataView = dataViewSelect.value;
const startDate = startDateInput.value;
const endDate = endDateInput.value;

showLoading(true);

try {
let url;
let data;

switch (dataView) {
case ‘category’:
url = ‘/api/sales/summary/category’;
break;
case ‘date’:
url = ‘/api/sales/summary/date’;
break;
case ‘all’:
if (startDate && endDate) {
url = `/api/sales/date-range?startDate=${startDate}&endDate=${endDate}`;
} else {
url = ‘/api/sales’;
}
break;
default:
url = ‘/api/sales/summary/category’;
}

const response = await fetch(url);
data = await response.json();

if (data.error) {
throw new Error(data.error);
}

currentData = data;
updateChart();
updateDataTable();

} catch (error) {
console.error(‘加载数据失败:’, error);
showMessage(`加载数据失败: ${error.message}`, ‘error’);
} finally {
showLoading(false);
}
}

// 更新图表
function updateChart() {
const chartType = chartTypeSelect.value;
const dataView = dataViewSelect.value;

if (!currentData || currentData.length === 0) {
showMessage(‘没有数据可显示’, ‘error’);
return;
}

// 准备图表数据
const chartData = prepareChartData(currentData, dataView);

// 销毁现有图表
if (mainChart) {
mainChart.destroy();
}

// 创建新图表
const ctx = document.getElementById(‘mainChart’).getContext(‘2d’);

// 根据图表类型设置不同的配置
let chartConfig;

switch (chartType) {
case ‘bar’:
chartConfig = createBarChartConfig(chartData);
break;
case ‘line’:
chartConfig = createLineChartConfig(chartData);
break;
case ‘pie’:
chartConfig = createPieChartConfig(chartData);
break;
case ‘doughnut’:
chartConfig = createDoughnutChartConfig(chartData);
break;
case ‘radar’:
chartConfig = createRadarChartConfig(chartData);
break;
default:
chartConfig = createBarChartConfig(chartData);
}

mainChart = new Chart(ctx, chartConfig);
}

// 准备图表数据
function prepareChartData(data, dataView) {
const labels = [];
const values = [];
const backgroundColors = [];
const borderColors = [];

// 颜色数组
const colors = [
‘rgba(255, 99, 132, 0.7)’,
‘rgba(54, 162, 235, 0.7)’,
‘rgba(255, 206, 86, 0.7)’,
‘rgba(75, 192, 192, 0.7)’,
‘rgba(153, 102, 255, 0.7)’,
‘rgba(255, 159, 64, 0.7)’,
‘rgba(199, 0, 57, 0.7)’,
‘rgba(0, 128, 128, 0.7)’
];

const borderColorsList = [
‘rgba(255, 99, 132, 1)’,
‘rgba(54, 162, 235, 1)’,
‘rgba(255, 206, 86, 1)’,
‘rgba(75, 192, 192, 1)’,
‘rgba(153, 102, 255, 1)’,
‘rgba(255, 159, 64, 1)’,
‘rgba(199, 0, 57, 1)’,
‘rgba(0, 128, 128, 1)’
];

if (dataView === ‘category’) {
// 按类别汇总
data.forEach((item, index) => {
labels.push(item.category || ‘未知’);
values.push(item.total_revenue);
backgroundColors.push(colors[index % colors.length]);
borderColors.push(borderColorsList[index % borderColorsList.length]);
});
} else if (dataView === ‘date’) {
// 按日期汇总
data.forEach((item, index) => {
labels.push(item.sale_date);
values.push(item.total_revenue);
backgroundColors.push(colors[index % colors.length]);
borderColors.push(borderColorsList[index % borderColorsList.length]);
});
} else {
// 全部数据
data.forEach((item, index) => {
labels.push(item.product_name);
values.push(item.quantity * item.price);
backgroundColors.push(colors[index % colors.length]);
borderColors.push(borderColorsList[index % borderColorsList.length]);
});
}

return {
labels,
datasets: [{
label: ‘销售额’,
data: values,
backgroundColor: backgroundColors,
borderColor: borderColors,
borderWidth: 2,
tension: 0.4
}]
};
}

// 创建柱状图配置
function createBarChartConfig(chartData) {
return {
type: ‘bar’,
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: ‘销售数据可视化’,
font: {
size: 18
}
},
legend: {
display: true,
position: ‘top’
},
tooltip: {
callbacks: {
label: function(context) {
return `销售额: $${context.parsed.y.toFixed(2)}`;
}
}
}
},
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function(value) {
return ‘$’ + value.toFixed(2);
}
}
}
}
}
};
}

// 创建折线图配置
function createLineChartConfig(chartData) {
return {
type: ‘line’,
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: ‘销售趋势图’,
font: {
size: 18
}
},
legend: {
display: true,
position: ‘top’
}
},
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function(value) {
return ‘$’ + value.toFixed(2);
}
}
}
}
}
};
}

// 创建饼图配置
function createPieChartConfig(chartData) {
return {
type: ‘pie’,
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: ‘销售占比图’,
font: {
size: 18
}
},
legend: {
display: true,
position: ‘right’
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || ”;
const value = context.parsed;
const total = context.dataset.data.reduce((a, b) => a + b, 0);
const percentage = ((value / total) * 100).toFixed(1);
return `${label}: $${value.toFixed(2)} (${percentage}%)`;
}
}
}
}
}
};
}

// 创建环形图配置
function createDoughnutChartConfig(chartData) {
return {
type: ‘doughnut’,
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: ‘销售占比环形图’,
font: {
size: 18
}
},
legend: {
display: true,
position: ‘right’
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || ”;
const value = context.parsed;
const total = context.dataset.data.reduce((a, b) => a + b, 0);
const percentage = ((value / total) * 100).toFixed(1);
return `${label}: $${value.toFixed(2)} (${percentage}%)`;
}
}
}
},
cutout: ‘50%’
}
};
}

// 创建雷达图配置
function createRadarChartConfig(chartData) {
return {
type: ‘radar’,
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: ‘销售雷达图’,
font: {
size: 18
}
},
legend: {
display: true,
position: ‘top’
}
},
scales: {
r: {
beginAtZero: true,
ticks: {
callback: function(value) {
return ‘$’ + value.toFixed(0);
}
}
}
}
}
};
}

// 更新数据表格
function updateDataTable() {
if (!currentData || currentData.length === 0) {
dataTableBody.innerHTML = ‘

暂无数据

‘;
return;
}

// 清空表格
dataTableBody.innerHTML = ”;

// 添加行
currentData.forEach(item => {
const row = document.createElement(‘tr’);

// 根据数据视图显示不同内容
const dataView = dataViewSelect.value;

if (dataView === ‘category’) {
row.innerHTML = `

– – ${item.total_quantity} – $${item.total_revenue.toFixed(2)} – ${item.category}

`;
} else if (dataView === ‘date’) {
row.innerHTML = `

– – ${item.total_quantity} – $${item.total_revenue.toFixed(2)} ${item.sale_date} –

`;
} else {
row.innerHTML = `

${item.id} ${item.product_name} ${item.quantity} $${item.price.toFixed(2)} $${(item.quantity * item.price).toFixed(2)} ${item.sale_date} ${item.category || ‘未知’}

`;
}

dataTableBody.appendChild(row);
});
}

// 处理添加销售记录
async function handleAddSale(e) {
e.preventDefault();

const productName = document.getElementById(‘productName’).value;
const quantity = parseInt(document.getElementById(‘quantity’).value);
const price = parseFloat(document.getElementById(‘price’).value);
const saleDate = document.getElementById(‘saleDate’).value;
const category = document.getElementById(‘category’).value;

if (!productName || !quantity || !price || !saleDate || !category) {
showMessage(‘请填写所有必填字段’, ‘error’);
return;
}

showLoading(true);

try {
const response = await fetch(‘/api/sales’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’
},
body: JSON.stringify({
product_name: productName,
quantity: quantity,
price: price,
sale_date: saleDate,
category: category
})
});

const result = await response.json();

if (result.error) {
throw new Error(result.error);
}

showMessage(‘销售记录添加成功!’, ‘success’);

// 重置表单
addSaleForm.reset();

// 刷新数据
loadChartData();

} catch (error) {
console.error(‘添加销售记录失败:’, error);
showMessage(`添加失败: ${error.message}`, ‘error’);
} finally {
showLoading(false);
}
}

// 显示加载状态
function showLoading(isLoading) {
if (isLoading) {
updateChartBtn.innerHTML = ‘更新中‘;
updateChartBtn.disabled = true;
refreshDataBtn.innerHTML = ‘刷新中‘;
refreshDataBtn.disabled = true;
} else {
updateChartBtn.innerHTML = ‘更新图表’;
updateChartBtn.disabled = false;
refreshDataBtn.innerHTML = ‘刷新数据’;
refreshDataBtn.disabled = false;
}
}

// 显示消息
function showMessage(message, type) {
// 移除现有的消息
const existingMessages = document.querySelectorAll(‘.error-message, .success-message’);
existingMessages.forEach(msg => msg.remove());

// 创建新消息
const messageDiv = document.createElement(‘div’);
messageDiv.className = type === ‘error’ ? ‘error-message’ : ‘success-message’;
messageDiv.textContent = message;

// 添加到页面顶部
const container = document.querySelector(‘.container’);
container.insertBefore(messageDiv, container.firstChild);

// 5秒后自动移除
setTimeout(() => {
if (messageDiv.parentNode) {
messageDiv.remove();
}
}, 5000);
}
6. 运行与测试
6.1 启动服务器
# 在项目根目录下运行
node server.js
6.2 访问应用
打开浏览器,访问
http://localhost:3000
6.3 功能测试
查看图表
:页面加载后会自动显示按类别汇总的柱状图
切换图表类型
:在”图表类型”下拉菜单中选择不同的图表类型
切换数据视图
:选择”按日期汇总”或”全部数据”查看不同视图
日期范围筛选
:设置日期范围后点击”更新图表”
添加新数据
:在表单中填写信息并提交,图表会自动更新
刷新数据
:点击”刷新数据”按钮重新加载所有数据
7. 高级功能扩展
7.1 实时数据更新
要实现实时数据更新,可以使用WebSocket或轮询机制:
// 在server.js中添加WebSocket支持
const WebSocket = require(‘ws’);
const wss = new WebSocket.Server({ port: 8080 });

// 当数据库更新时通知所有客户端
function notifyClients(data) {
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: ‘update’, data }));
}
});
}

// 在添加销售记录的API中调用notifyClients
app.post(‘/api/sales’, (req, res) => {
// … 现有代码 …
db.addSale(product_name, quantity, price, sale_date, category, (err, result) => {
if (err) {
res.status(500).json({ error: err.message });
} else {
// 通知所有客户端数据已更新
notifyClients({ type: ‘new_sale’, id: result.id });
res.json({ message: ‘销售记录添加成功’, id: result.id });
}
});
});
7.2 数据导出功能
添加数据导出为CSV或JSON的功能:
// 在server.js中添加导出API
app.get(‘/api/sales/export/csv’, (req, res) => {
db.getAllSales((err, data) => {
if (err) {
res.status(500).json({ error: err.message });
return;
}

// 转换为CSV格式
const headers = [‘ID’, ‘产品名称’, ‘数量’, ‘单价’, ‘销售日期’, ‘类别’];
const csvContent = [
headers.join(‘,’),
…data.map(row => [
row.id,
`”${row.product_name}”`,
row.quantity,
row.price,
row.sale_date,
`”${row.category}”`
].join(‘,’))
].join(‘\n’);

res.setHeader(‘Content-Type’, ‘text/csv’);
res.setHeader(‘Content-Disposition’, ‘attachment; filename=”sales_data.csv”‘);
res.send(csvContent);
});
});
7.3 数据验证与安全性
增强数据验证和安全性:
// 在server.js中添加输入验证中间件
function validateSaleData(req, res, next) {
const { product_name, quantity, price, sale_date, category } = req.body;

// 验证产品名称
if (!product_name || typeof product_name !== ‘string’ || product_name.trim().length === 0) {
return res.status(400).json({ error: ‘产品名称不能为空’ });
}

// 验证数量
if (!quantity || isNaN(quantity) || quantity <= 0) { return res.status(400).json({ error: '数量必须是正整数' }); } // 验证价格 if (!price || isNaN(price) || price <= 0) { return res.status(400).json({ error: '价格必须是正数' }); } // 验证日期格式 const dateRegex = /^\d{4}-\d{2}-\d{2}$/; if (!sale_date || !dateRegex.test(sale_date)) { return res.status(400).json({ error: '日期格式必须为YYYY-MM-DD' }); } // 验证日期是否在合理范围内 const selectedDate = new Date(sale_date); const today = new Date(); if (selectedDate > today) {
return res.status(400).json({ error: ‘销售日期不能是未来日期’ });
}

next();
}

// 应用验证中间件
app.post(‘/api/sales’, validateSaleData, (req, res) => {
// … 现有代码 …
});
8. 性能优化建议
8.1 数据库优化
索引优化
:为常用查询字段添加索引
CREATE INDEX idx_sales_date ON sales(sale_date);
CREATE INDEX idx_sales_category ON sales(category);
CREATE INDEX idx_sales_product ON sales(product_name);
分页查询
:对于大量数据,实现分页
// 在db.js中添加分页查询
getSalesWithPagination: function(page, pageSize, callback) {
const offset = (page – 1) * pageSize;
const sql = `SELECT * FROM sales ORDER BY sale_date DESC LIMIT ? OFFSET ?`;
db.all(sql, [pageSize, offset], (err, rows) => {
if (err) {
callback(err, null);
} else {
callback(null, rows);
}
});
}
8.2 前端优化
数据缓存
:缓存已加载的数据,避免重复请求
懒加载
:对于大数据集,实现懒加载
图表优化
:使用Chart.js的动画和过渡效果提升用户体验
9. 常见问题与解决方案
9.1 数据库连接问题
问题
:无法连接到SQLite数据库
解决方案
:
检查文件权限
确保数据库文件路径正确
检查是否有其他进程占用数据库文件
9.2 图表不显示
问题
:图表区域空白
解决方案
:
检查Chart.js是否正确加载
确保Canvas元素存在
检查数据格式是否正确
9.3 跨域问题
问题
:前端无法访问后端API
解决方案
:
确保已安装并使用cors中间件
检查端口配置是否正确
10. 总结
本文详细介绍了如何将Chart.js与SQLite集成,构建一个完整的数据可视化解决方案。通过这个示例项目,我们学习了:
数据库设计
:如何设计适合图表展示的数据结构
后端API开发
:使用Node.js和Express创建RESTful API
前端集成
:使用Chart.js创建动态交互式图表
数据流管理
:从数据库到前端图表的完整数据流
用户体验优化
:添加加载状态、错误处理和用户反馈
这个解决方案可以作为基础,根据具体需求进行扩展,例如:
添加用户认证和权限管理
实现更复杂的数据分析和聚合
集成更多图表类型和可视化选项
添加数据导出和报表生成功能
通过将Chart.js与SQLite结合,我们创建了一个轻量级但功能强大的数据可视化系统,适用于各种小型到中型的应用场景。