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

来源:互联网 发布:mac终端 ip地址配置 编辑:程序博客网 时间:2024/05/02 16:44
<%@ 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
原创粉丝点击