创建ashx文档对OleDb数据库进行操作

<%@ 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";		
		
		//连接OleDb数据库
		OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=E:\\study\\jq_ashx\\db1.mdb");
		
		//接受前端页面发送来的参数
		string add_content = context.Request.Form["info"];
		string del_content = context.Request.Form["del_info"];
		string search_content = context.Request.Form["search_info"];
		string change_b_content = context.Request.Form["change_b"];
		string change_a_content = context.Request.Form["change_a"];

		//数据库的增删查改的sql语句
		string sql_add = "insert into table1(information) values('" + add_content + "')";
		string sql_del = "delete from table1 where information='" + del_content + "'";
		string sql_search = "select information from table1";
		string sql_change = "update table1 set information='" + change_a_content + "' where information='" + change_b_content + "'";
		
		try{
			connection.Open();
			//插入
			if(add_content != null){
				OleDbCommand cmd_add = new OleDbCommand(sql_add,connection);
				cmd_add.ExecuteNonQuery();
			}

			//删除
			if(del_content != null){
				OleDbCommand cmd_del = new OleDbCommand(sql_del,connection);
				cmd_del.ExecuteNonQuery();
			}

			//查询
			if(search_content != null){
				OleDbCommand cmd_search = new OleDbCommand(sql_search,connection);
				OleDbDataReader reader = cmd_search.ExecuteReader();
				
				string result = "no exist";		//默认不存在,如果在数据库查找到则会替换变量的值
				while(reader.Read()){
					string readerVal = reader.GetValue(0).ToString();//GetValue(i)从结果的第i+1个字段获取
					if(search_content == readerVal){
						result = "exist!";
						break;
					}
				}
				context.Response.Write(result);
			}

			//替换
			if(change_a_content != null & change_b_content != null){
				OleDbCommand cmd_change = new OleDbCommand(sql_change,connection);
				cmd_change.ExecuteNonQuery();
			}
		}
		catch (Exception exp){
            context.Response.Write(exp.Message);
        }

        finally{
        	connection.Close();
        }
	}

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


总结:关于OleDbCommand类,增,改,替换操作,只需调用类里的ExecuteNonQuery()方法.而对于查询操作,则须声明OleDbDataReader下的一个参数,并调用类里的ExecuteReader()方法,最后利用循环将数据输出.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值