如何调用数据库访问类?
这是个封装的数据库访问类:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace Dblist
{
/// <summary>
/// DbList_Cla 的摘要说明。
/// </summary>
public class DbList_Cla
{
private string ConnStr = null;
public DbList_Cla()
{
ConnStr = "server=localhost;database=mydatabase;uid=sa;pwd=";
ConnStr = ConfigurationSettings.AppSettings["ConnStr"];
}
public DbList_Cla(string Str)
{
try
{
this.ConnStr = Str;
}
catch(Exception ex)
{
throw ex;
}
}
public SqlConnection ReturnConn()
{
SqlConnection Conn = new SqlConnection(ConnStr);
Conn.Open();
return Conn;
}
public void Dispose(SqlConnection Conn)
{
if(Conn!=null)
{
Conn.Close();
Conn.Dispose();
}
GC.Collect();
}
public void RunProc(string SQL)
{
SqlConnection Conn;
Conn = new SqlConnection(ConnStr);
Conn.Open();
SqlCommand Cmd ;
Cmd = CreateCmd(SQL, Conn);
try
{
Cmd.ExecuteNonQuery();
}
catch
{
throw new Exception(SQL);
}
Dispose(Conn);
return;
}
public SqlDataReader RunProcGetReader(string SQL)
{
SqlConnection Conn;
Conn = new SqlConnection(ConnStr);
Conn.Open();
SqlCommand Cmd ;
Cmd = CreateCmd(SQL, Conn);
SqlDataReader dr;
try
{
dr = Cmd.ExecuteReader(CommandBehavior.Default);
}
catch
{
throw new Exception(SQL);
}
//Dispose(Conn);
return dr;
}
public SqlCommand CreateCmd(string SQL, SqlConnection Conn)
{
SqlCommand Cmd ;
Cmd = new SqlCommand(SQL, Conn);
return Cmd;
}
........
}
}
//
如何来调用?
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Dblist;
namespace Friend
{
/// <summary>
/// _Default 的摘要说明。
/// </summary>
public class _Default : System.Web.UI.Page
{
public DbList_Cla my=new DbList_Cla();
public DbList_Cla dr=new DbList_Cla();
protected System.Web.UI.WebControls.TextBox UserName;
protected System.Web.UI.WebControls.ImageButton ImageButton1;
protected System.Web.UI.WebControls.TextBox PassWord;
protected System.Web.UI.WebControls.ImageButton ImgBt4;
protected System.Web.UI.WebControls.ImageButton ImgBtn4;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
private void ImageButton1_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
//想在这里实现按钮提交后,获取用户表中的用户名
}
}
}
如何实现?
问题点数:20、回复次数:5Top
1 楼Anders_lt(突破渴望)回复于 2006-03-21 14:04:44 得分 0
新建一个类DbList_Cla 的对象,就可以访问它的方法了
Top
2 楼fellowcheng(鹰击长空)回复于 2006-03-21 14:18:10 得分 10
DbList_Cla db = new DbList_Cla();
//执行普通SQL
db.RunProc("...");
//返回DataReader的SQL
SqlDataReader rdr = db. RunProcGetReader("...");Top
3 楼championchen79(现学现卖)回复于 2006-03-21 14:20:00 得分 10
DbList_Cla mydata= new DbList_Cla(); //先实例化数据类
SqlDataReader mydr = mydata.RunProcGetReader("select 用户名 from 用户表"); //调用类里的方法Top
4 楼91bct(Jerry)回复于 2006-03-21 14:30:31 得分 0
楼上都对。
记得添加引用名字空间:Dblist
Top
5 楼chjp_68()回复于 2006-03-21 14:51:07 得分 0
OKTop




