有个网站是分三层架构实现的,其中数据访问层是一些基础的访问数据库的类组成,这些类以前从未进行异常检测和处理,请问是否需要添加异常处理,如果需要,能写个例子给我看看,真心求教大虾们!
public class DBase
{
public DBase(string str)
{
dbstr=str;
}
private OleDbConnection con;
private string dbstr;
OleDbCommand cmd;
public void Open()
{
if (con == null)
{
string constr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+dbstr;
con = new OleDbConnection(constr);
}
if (con.State == ConnectionState.Closed)
con.Open();
}
public void Close()
{
if (con != null)
con.Close();
}
public void Dispose()
{
if (con != null)
{
con.Dispose();
}
}
public OleDbParameter MakeInParam(string ParamName, OleDbType DbType, int Size, object Value)
{
OleDbParameter param = new OleDbParameter();
param.ParameterName=ParamName;
param.OleDbType=DbType;
param.Size=Size;
param.Value=Value;
return param;
}
public int ReadCount(string Sqlstr, OleDbParameter[] Params)
{
cmd = new OleDbCommand();
cmd.Connection = con;
foreach (OleDbParameter param in Params)
cmd.Parameters.Add(param);
cmd.CommandText = Sqlstr;
OleDbDataReader rd = cmd.ExecuteReader();
rd.Read();
int count= rd.GetInt32(0);
rd.Dispose();
cmd = null;
return count;
}
public OleDbDataReader CreateReader1(string Sqlstr, OleDbParameter[] Params)
{
cmd = new OleDbCommand();
cmd.Connection = con;
foreach (OleDbParameter param in Params)
cmd.Parameters.Add(param);
cmd.CommandText = Sqlstr;
OleDbDataReader rd = cmd.ExecuteReader();
return rd;
}
public OleDbDataReader CreateReader2(string Sqlstr)
{
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = Sqlstr;
OleDbDataReader rd = cmd.ExecuteReader();
return rd;
}
public bool Createbool(string Sqlstr, OleDbParameter[] Params)
{
cmd = new OleDbCommand();
cmd.Connection = con;
foreach (OleDbParameter param in Params)
cmd.Parameters.Add(param);
cmd.CommandText = Sqlstr;
try
{
OleDbDataReader rd = cmd.ExecuteReader();
return true;
}
catch
{
return false;
}
}
在此基础上能加上异常处理吗?
像这些 Open() 之类的方法,都不是线程安全的,catch{rturn false;}之流就别写了,到UI或业务层去catch.
这个类设计的比较“业余”,还是直接使用ORM的好,或者参考下微软的SqlHelper使用数据库的方式。