c# 查询SQLserver数据库,利用echarts生成图标。请举例说明
时间: 2024-05-06 16:16:48 浏览: 251
C#上的echarts的例子
3星 · 编辑精心推荐
假设你已经连接到 SQL Server 数据库并且安装了 ECharts,以下是一个简单的 C# 查询 SQL Server 数据库并使用 ECharts 生成图表的示例:
```csharp
using System.Data.SqlClient;
using System.Web.Script.Serialization;
// 连接数据库
SqlConnection conn = new SqlConnection("Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;");
conn.Open();
// 查询数据
string query = "SELECT category, value FROM myTable";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader reader = cmd.ExecuteReader();
// 处理数据
List<object[]> data = new List<object[]>();
while (reader.Read())
{
string category = reader.GetString(0);
int value = reader.GetInt32(1);
data.Add(new object[] { category, value });
}
// 生成 ECharts 配置
Dictionary<string, object> option = new Dictionary<string, object>();
option.Add("tooltip", new Dictionary<string, object>() {
{"trigger", "axis"}
});
option.Add("xAxis", new Dictionary<string, object>() {
{"type", "category"},
{"data", data.Select(x => x[0]).ToArray()}
});
option.Add("yAxis", new Dictionary<string, object>() {
{"type", "value"}
});
option.Add("series", new Dictionary<string, object>[] {
new Dictionary<string, object>() {
{"name", "mySeries"},
{"type", "bar"},
{"data", data.Select(x => x[1]).ToArray()}
}
});
// 转换配置为 JSON 字符串
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(option);
// 在页面上渲染 ECharts
string html = $@"
<html>
<head>
<script src=""https://cdn.jsdelivr.net/npm/echarts@5.1.0/dist/echarts.min.js""></script>
</head>
<body>
<div id=""myChart"" style=""width: 600px; height: 400px;""></div>
<script>
var option = {json};
var chart = echarts.init(document.getElementById('myChart'));
chart.setOption(option);
</script>
</body>
</html>
";
// 渲染 HTML
Response.Write(html);
```
请注意,这只是一个简单的示例,实际应用中可能需要更多的错误处理、数据验证和安全措施。
阅读全文