buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

在运行时获取ibatIS执行的sql

如下方法可以在运行时获取ibatIS执行的sql:

/// <summary>
/// 获取运行时的sql语句
/// </summary>
/// <param name="readOrWriterName">读/写配置文件</param>
/// <param name="statementName">sqlmap中的sql位置</param>
/// <param name="paramObject">执行statementName对应的sql时传递的参数</param>
/// <returns></returns>
public string GetRuntimeSql(string readOrWriterName, string statementName, object paramObject)
{
string result = string.Empty;
ISqlMapper sqlMapper = new DomSqlMapBuilder().Configure(readOrWriterName);
try
{
IMappedStatement statement = sqlMapper.GetMappedStatement(statementName);

if (!sqlMapper.IsSessionStarted)
{
sqlMapper.OpenConnection();
}

RequestScope scope = statement.Statement.Sql.GetRequestScope(statement, paramObject, sqlMapper.LocalSession);
result = scope.PreparedStatement.PreparedSql;
}
catch (Exception ex)
{
result = "获取SQL语句出现异常:" + ex.Message;
}

return result;
}


需引入如下4个namespace:

using IBatisNet.DataMapper;
using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataMapper.MappedStatements;
using IBatisNet.DataMapper.Scope;

调用方式:

string sql = this.GetRuntimeSql("ModifyReader.config", "InOutStockDao.AddOutput", m);



  利用此方法可以监测到运行时的sql语句,但如果有参数传入,则不会获取到参数的值。

  若database为sqlserver, 也可以利用sqlserver的profiler工具(sqlserver2000里叫事件探查器),进行监测。当然,这需要您具有相关权限。与上面的方法不同,这里监测到的sql是最终的可执行的sql语句。

posted on 2011-12-20 13:33  buguge  阅读(2868)  评论(0编辑  收藏  举报