黑马程序员技术交流社区
标题:
我写的一个数据库连接层,大家给点建议
[打印本页]
作者:
笔墨伺候
时间:
2012-10-18 14:08
标题:
我写的一个数据库连接层,大家给点建议
DB.cs(这个是关于access的数据库连接层)
using System;
using System.Collections.Generic;
using System.Web;
using System.Data.OleDb;
using System.Data;
namespace test9
{
public class DB
{
//连接字符串
// private string conString = ConfigurationManager.ConnectionStrings["site"].ConnectionString;
private string conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + HttpContext.Current.Server.MapPath("~/App_Data/site.mdb");
private OleDbConnection con;
//打开一个数据库连接
private void open()
{
if (this.con == null)
{
this.con = new OleDbConnection(conString);
}
this.con.Open();
}
//关闭一个数据库连接
private void close()
{
if (this.con.State != ConnectionState.Closed)
{
this.con.Close();
}
}
//无返回值查询
public void noneQ(string sql, params OleDbParameter[] sps)
{
this.open();
using (OleDbCommand cmd = new OleDbCommand(sql, this.con))
{
foreach (OleDbParameter sp in sps)
{
cmd.Parameters.Add(sp);
}
cmd.ExecuteNonQuery();
}
this.close();
}
//返回单个值查询
public object oneQ(string sql, params OleDbParameter[] sps)
{
object re;
this.open();
using (OleDbCommand cmd = new OleDbCommand(sql, this.con))
{
foreach (OleDbParameter sp in sps)
{
cmd.Parameters.Add(sp);
}
re = cmd.ExecuteScalar();
}
this.close();
return re;
}
//返回一个DataTable
public DataTable excuteTable(string sql, params OleDbParameter[] sps)
{
DataTable table;
this.open();
using (OleDbCommand cmd = new OleDbCommand(sql, this.con))
{
foreach (OleDbParameter sp in sps)
{
cmd.Parameters.Add(sp);
}
DataSet ds = new DataSet();
OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
sda.Fill(ds);
table = ds.Tables[0];
}
this.close();
return table;
}
public DataTable excuteTable(string sql)
{
DataTable table;
this.open();
using (OleDbCommand cmd = new OleDbCommand(sql, this.con))
{
DataSet ds = new DataSet();
OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
sda.Fill(ds);
table = ds.Tables[0];
}
this.close();
return table;
}
//带有事务
public string transaction(params string[] cmds)
{
this.open();
OleDbTransaction ot = con.BeginTransaction();
OleDbCommand cmd = new OleDbCommand();
cmd.Transaction = ot;
cmd.Connection = con;
try
{
foreach (string cm in cmds)
{
cmd.CommandText = cm;
cmd.ExecuteNonQuery();
}
ot.Commit();
return "操作成功";
}
catch (Exception ex)
{
ot.Rollback();
return "操作失败,错误信息:" + ex.Message;
}
finally
{
this.close();
}
}
}
}
复制代码
大家给提点建议,毕竟这些东西是可以重用的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2