20151229:AJax :用类方式做一个查询
前台aspx代码不变,处理页面需要新建一个类,封装属性并在处理页面调用
新建类DB代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data;//引用命名空间 using System.Data.SqlClient; /// <summary> /// DB 的摘要说明 /// </summary> public class DB { public DB() { // // TODO: 在此处添加构造函数逻辑 // } public string SqlDB(string database,string type,string sql) { string connstring = "server=.\\SQL;database="+database+";uid=sa;pwd=123"; SqlConnection conn = new SqlConnection(connstring); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; string shuju = ""; conn.Open(); if (type == "CX") { SqlDataReader _dr = cmd.ExecuteReader(); while (_dr.Read())//遍历每一行 { for (int i = 0; i < _dr.FieldCount; i++)//遍历每一列 {//某一列的值_dr[i] 把数据里面拼上每一列的数据 shuju += _dr[i].ToString() + "^"; } shuju = shuju.Substring(0, shuju.Length - 1); shuju += "|"; } shuju = shuju.Substring(0, shuju.Length - 1);//去掉最后一个"|" } else { int a = cmd.ExecuteNonQuery(); if (a > 0) { shuju = "成功"; } else { shuju = "失败"; } } conn.Close(); return shuju; } }
处理界面Select代码:
<%@ WebHandler Language="C#" Class="Select" %> using System; using System.Web; using System.Linq;//引用命名空间 using System.Data.Linq; public class Select : IHttpHandler { public void ProcessRequest (HttpContext context) { //取值 string name = context.Request["Name"].ToString(); //用类的方法 //做一个SQL语句 string sql = "select *from Info where Name like '%" + name + "%'"; //调DB类里面的函数 DB cmd = new DB(); //函数需要三个参数 返回一个字符串 string shuju = cmd.SqlDB("mydb","CX",sql); //输入字符串 context.Response.Write(shuju); context.Response.End(); } public bool IsReusable { get { return false; } } }
网页中显示效果不变: