利用ashx操作OleDb数据库返回json数据

本文介绍如何在ASP.NET中通过ASHX处理程序与OleDb数据库进行交互,以获取符合JQ插件dataTables要求的JSON格式数据。

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

因为是套用JQ插件dataTables,所以这里的json格式会有点区别

<%@ WebHandler Language="C#" Class="data" %>

using System;
using System.Web;
using System.Data;
using System.Data.OleDb;

public class data : IHttpHandler{
	
	public void ProcessRequest(HttpContext context){
		context.Response.ContentType = "text/plain";
		OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=E:\\study\\jq_ashx\\db1.mdb");
	
		string sql_search = "select information from table1";
		string sql_count = "select count(*) from table1";		//统计个数

		try{
			connection.Open();
			//读取数据库内容并输出
			OleDbCommand cmd_test = new OleDbCommand(sql_search,connection);
			OleDbDataReader reader = cmd_test.ExecuteReader();
			OleDbCommand cmd_count = new OleDbCommand(sql_count,connection);
			string count = cmd_count.ExecuteScalar().ToString();
			
			string readerHead = "{\"data\":[";
			context.Response.Write(readerHead);
			int i = 0;
			while(reader.Read()){
				string readerVal;
				i = i+1;
				//如果是最后一组数据,输出最后不带逗号
				if(i == int.Parse(count)){
					readerVal = "[" + "\"" + reader.GetValue(0).ToString()+ "\"" + "]";
					context.Response.Write(readerVal);	
				}
				else{
					readerVal = "[" + "\"" + reader.GetValue(0).ToString()+ "\"" + "],";
					context.Response.Write(readerVal);
				}
			}
			string readerLeg = "]}";
			context.Response.Write(readerLeg);

		}
		catch (Exception exp){
            context.Response.Write(exp.Message);
        }

        finally{
        	connection.Close();
        }
	}

	public bool IsReusable {
        get {
            return false;
        }
    }	
}

只要重复使用context.Response.Write()即可输出json格式的数据了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值