界面--应用程序--数据库
人们笑我太疯癫...我笑人们太正经
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataAccess
{
/// <summary>
/// SQL Server 数据库的访问类
/// </summary>
public class SqlAccess
{
private SqlConnection SqlCon;
private SqlDataAdapter SqlAdp;
private SqlCommand SqlCmd;
private SqlCommandBuilder SqlCmdB;
public SqlAccess()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
protected SqlConnection getConnection()
{
if(this.SqlCon==null)
{
this.SqlCon=new SqlConnection(this.ConStr);
this.SqlCon.Open();
}
return this.SqlCon;
}
protected SqlDataAdapter getDataAdapter()
{
this.SqlCon=(SqlConnection)this.getConnection();
this.SqlAdp=new SqlDataAdapter(this.SqlStr,this.SqlCon);
return this.SqlAdp;
}
protected SqlCommand getCommand()
{
this.SqlCon=(SqlConnection)this.getConnection();
this.SqlCmd=new SqlCommand(this.SqlStr,this.SqlCon);
return this.SqlCmd;
}
protected SqlCommandBuilder getCommandBuilder()
{
this.SqlAdp=(SqlDataAdapter)this.getDataAdapter();
this.SqlCmdB=new SqlCommandBuilder(this.SqlAdp);
return this.SqlCmdB;
}
protected DataSet getDataSet()
{
this.SqlAdp=(SqlDataAdapter)this.getDataAdapter();
this.ObjDs=new DataSet();
this.SqlAdp.Fill(this.ObjDs,this.TBName);
return this.ObjDs;
}
protected void SetActionCommand()
{
switch(this.ActionMode)
{
case "Insert":
this.SqlAdp.InsertCommand=this.SqlCmdB.GetInsertCommand();
break;
case "Update":
this.SqlAdp.UpdateCommand=this.SqlCmdB.GetUpdateCommand();
break;
case "Delete":
this.SqlAdp.DeleteCommand=this.SqlCmdB.GetDeleteCommand();
break;
}
}
public DataTable getDataTable()
{
this.ObjDs=this.getDataSet();
return this.ObjDs.Tables[this.TBName];
}
public void SaveTable(DataSet srcDts)
{
this.SqlAdp=(SqlDataAdapter)this.getDataAdapter();
this.SqlCmdB=(SqlCommandBuilder)this.getCommandBuilder();
this.SetActionCommand();
this.SqlAdp.Update(srcDts,this.TBName);
}
}
}
个人的数据层常用代码,这个类的优点在于,只用一个函数就可以直接得到DataTable,个人觉得.NET里Connection对象可以用单例模式来做。