您的位置:首页 > 数据库

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

2014-12-27 11:07 369 查看
<%@ 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()方法,最后利用循环将数据输出.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐