我常用的conn.cs数据库操作类库

发布时间:2008年01月24日      浏览次数:1789 次
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.OleDb;
namespace My_DataBase
{
/// <summary>
/// MDB_DataBase 的摘要说明
/// </summary>
public class DataBase
{
private int intCount = 0;
public DataBase()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 公开方法DBConn,返回数据库连接
/// </summary>
public OleDbConnection DBconn()
{
//string strConn = "Server=(local);Database=GlobalMeetings;Uid=sa;pwd=";//SQL数据库链接
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + HttpContext.Current.Server.MapPath("App_Data/web@data.mdb");//Access数据库链接
try
{
return new OleDbConnection(strConn);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 根据查询语句从数据库检索数据
/// </summary>
/// <param name="strSelect">查询语句</param>
/// <param name="SqlConn">数据库连接</param>
/// <returns>有数据则返回DataSet对象,否则返回null</returns>
public DataSet Select(string SelectString, OleDbConnection sqlConn)
{
OleDbConnection conn;
if (sqlConn == null)
{
conn = DBconn();
}
else
{
conn = sqlConn;
}
try
{
//若数据库连接的当前状态是关闭的,则打开连接
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OleDbDataAdapter myOleDbDataAdapter = new OleDbDataAdapter();
OleDbCommand selectCommand = new OleDbCommand(SelectString, conn);
selectCommand.CommandType = CommandType.Text;
myOleDbDataAdapter.SelectCommand = selectCommand;
DataSet myDS = new DataSet();
myOleDbDataAdapter.Fill(myDS);
return myDS;
}
catch (Exception e)
{
return null;
}
finally
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
}
/// <summary>
/// 更新数据库
/// </summary>
public bool Update(string UpdateString, OleDbConnection SqlConn)
{
return Execute(UpdateString, SqlConn);
}
/// <summary>
/// 从数据库中删除数据
/// </summary>
public bool Delete(string DeleteString, OleDbConnection SqlConn)
{
return Execute(DeleteString, SqlConn);
}
/// <summary>
/// 把数据插入数据库
/// </summary>
public bool Insert(string InsertString, OleDbConnection SqlConn)
{
return Execute(InsertString, SqlConn);
}
/// <summary>
/// 执行Sql语句
/// </summary>
public bool Execute(string UDIString, OleDbConnection SqlConn)
{
OleDbConnection conn;
if (SqlConn == null)
{
conn = DBconn();
}
else
{
conn = SqlConn;
}
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OleDbCommand cmd = new OleDbCommand(UDIString, conn);
cmd.CommandType = CommandType.Text;
intCount = cmd.ExecuteNonQuery();
return !(intCount < 1);
}
catch (Exception e)
{
return false;
}
finally
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
}
}
}
文章来源:桂林唯创网络
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!