前台代码不变 , 后台C# 代码需要建一个类 网页显示效果不变
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=.;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++) { 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页面 也要变:
using System.Data; using System.Data.SqlClient; 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; } }