ControlDBS.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Data;//
using System.Data.OleDb;//
namespace Links
{
public class ControlDBS
{
//定义链接字符串
OleDbConnection con;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="path">数据库路径</param>
public ControlDBS(string path)
{
con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path);
}
/// <summary>
/// 获取sql查询数据到数据表
/// </summary>
/// <param name="sqltext">SQL语句</param>
/// <returns>数据表</returns>
public DataTable selectTable(string sqltext)
{
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(sqltext, con);
try
{
con.Open();
adp.Fill(dt);
return dt;
}
catch (Exception e)
{
throw new SystemException(e.Message);
}
finally
{
con.Close();
}
}
/// <summary>
/// 获取数据到数据集
/// </summary>
/// <param name="sqltext">SQL语句</param>
/// <returns>数据集</returns>
public DataSet GetDataSet(string sqltext)
{
DataSet ds = new DataSet();
OleDbDataAdapter adp = new OleDbDataAdapter(sqltext, con);
try
{
con.Open();
adp.Fill(ds);
return ds;
}
catch (Exception e)
{
throw new SystemException(e.Message);
}
finally
{
con.Close();
}
}
/// <summary>
/// 返回sql查询的第一行第一列
/// </summary>
/// <param name="sqltext">SQL语句</param>
/// <returns>第一行第一列的字符串</returns>
public string GetFirstValue(string sqltext)
{
string strchar = "";
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = sqltext;
try
{
con.Open();
strchar = cmd.ExecuteScalar().ToString();
}
catch (Exception e)
{
throw new SystemException(e.Message);
}
finally
{
con.Close();
}
return strchar;
}
/// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="sqltext">SQL语句</param>
public void RunSqlCmd(string sqltext)
{
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = sqltext;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
throw new SystemException(e.Message);
}
finally
{
con.Close();
}
}
}
}
简单使用:
protected void Button1_Click(object sender, EventArgs e)
{
ControlDBS cd = new ControlDBS();
string sql = "select * from T1";//参数1
OleDbConnection con = cd.strcon(@Server.MapPath("/App_Data/Database1.mdb"));//参数2
DataTable dt = cd.GetDataTable(sql, con);
GridView1.DataSource = dt;
GridView1.DataBind()
}