using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.Script.Serialization;
public partial class DatabaseToJson : System.Web.UI.Page
{
[WebMethod]
public static string GetData()
{
// 假设你已经有了数据库连接字符串
string connectionString = "你的数据库连接字符串";
// 创建查询
string query = "SELECT * FROM YourTableName";
// 创建一个DataTable来存储数据
DataTable dataTable = new DataTable();
// 使用SqlDataAdapter来填充DataTable
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(dataTable);
}
}
}
// 将DataTable转换为JSON
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(dataTable);
}
}
在你的ASPX页面中,你可以使用以下HTML和JavaScript来创建介绍并显示JSON数据: