比如有一个类,用以数据访问:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace DbBase
public class Base
{
protected static string strConn = ConfigurationSettings.AppSettings["ConnectionSQLServer"];
protected static string strSQL;
public Base()
{
}
public DataSet ExecuteSql4Ds(string strSQL)
{
SqlConnection myCn = new SqlConnection(strConn);
try
{
myCn.Open();
SqlDataAdapter sda = new SqlDataAdapter(strSQL,myCn);
DataSet ds = new DataSet("ds");
sda.Fill(ds);
return ds;
}
catch(System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);//出错时我怎么得到e.Message?
}
finally
{
myCn.Close();
}
}
}
我在WEB页面中调用它:
Base SqlBase = new Base();
string strSql="select * from table";
DataGrid1.DataSource =SqlBase.ExecuteSql4Ds (strSql);
DataGrid1.DataBind ();
若不出错则正常,但若出错时,比如表名不存在,我怎么得到出错信息e.Message?让它显示在页面上的一个文本框或标签中?
在WEB页面中加出错处理;
try{
Base SqlBase = new Base();
string strSql="select * from table";
DataGrid1.DataSource =SqlBase.ExecuteSql4Ds (strSql);
DataGrid1.DataBind ();
}catch(Exception ex){
Response.Write("<script language=javascript>alert(" + ex.Message.ToString() + ")</script>");
}
catch(Exception ex)中的语句你可以自己定义,输出到文本框什么的也可以
数据层:
public ResultSet ExecQuery(string sql,ReturnType returnType)
{
ResultSet rs = new ResultSet(returnType);
try
{
OpenConnection();
SqlCommand.CommandType = CommandType.Text;
SqlCommand.CommandText = sql;
SqlCommand.Connection = Conn;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql,Conn);
switch(returnType)
{
case ReturnType.DataReader :
rs.DataReader = _sqlCommand.ExecuteReader();
break;
case ReturnType.DataSet :
sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
sqlDataAdapter.Fill(rs.DataSet);
break;
case ReturnType.OutputParameter :
_sqlCommand.ExecuteNonQuery();
SetOutputValue(rs);
break;
case ReturnType.SingleValue :
rs.Value = _sqlCommand.ExecuteScalar();
break;
default:
break;
}
rs.IsSucceed = true;
return rs;
}
catch(SqlException se)
{
_errorDescription = se.Message;
rs.IsSucceed = true;
return rs;
}
finally
{
CloseConnection();
}
}
/// <summary>
/// 定义数据库操作错误描述信息
/// </summary>
private string _errorDescription;
/// <summary>
/// 定义数据库操作错误描述信息
/// </summary>
public string ErrorDescription
{
get
{
return _errorDescription;
}
}
逻辑层:
errorMessage = db.ErrorDescription;
在调用ExecuteSql4Ds的地方
再
try
{}
catch()
{}