记录 NHibernate SQL 查询

15

在我的代码中是否有一种方式可以访问完整的SQL查询,包括值?

我能够使用log4net记录SQL查询:

<logger name="NHibernate.SQL" additivity="false">
    <level value="ALL"/>
    <appender-ref ref="NHibernateSQLFileLog"/>
</logger>

不过,我希望找到一种方式也能够从代码中记录SQL查询。这样一来,在我的try/catch语句中,我就可以记录导致异常的具体SQL查询。

目前,当异常发生时,我需要在SQLFileLog中进行数据挖掘,以找到导致异常的查询,这不是很高效。


请提供更多上下文信息。 - Mauricio Scheffer
4个回答

11

您可以使用拦截器来实现此功能:

public class LoggingInterceptor : EmptyInterceptor {
    public override SqlString OnPrepareStatement(SqlString sql) {
        
        Debug.WriteLine(sql);

        return sql;
    }
}

请查看Nhibernate文档(webarchive),了解在nhibernate中注册的不同方式。


9
能否捕获参数的值? - user39880
未找到http://www.nhforge.org/doc/nh/en/index.html#objectstate-interceptors,有没有使用LoggingInterceptor的示例? - Kiquenet

7
你可以重写驱动程序:
public class LoggerSqlClientDriver:SqlClientDriver, IEmbeddedBatcherFactoryProvider
{      
    public override void AdjustCommand(IDbCommand command)
    {
        //log here
        base.AdjustCommand(command);
    }

    //protected override void OnBeforePrepare(IDbCommand command)
    //{
    //    //log here
    //    base.OnBeforePrepare(command);
    //}
}

然后在配置中使用它:

var config = Fluently.Configure().
            Database(MsSqlConfiguration.MsSql2005.Driver<LoggerSqlClientDriver>();

4

可以使用SQL Profiler或查看nhprof网站上的内容,该网站地址为http://nhprof.com/

两种方法都可以让您查看SQL输出结果。

此外,还需要在Hibernate配置文件中设置show_sql属性。

<property name="show_sql">true</property>

1
我在代码中使用了以下语句: configuration = new Cfg.Configuration(); configuration.SetProperty(Cfg.Environment.ShowSql, "true"); _sessionFactory = configuration.BuildSessionFactory(); log4net.Config.XmlConfigurator.Configure();,但是没有生效。 - Kiquenet

1
使用特定目标的log4net appender(如果我没记错,它支持开关)或者只需扩展它并在try-catch-finally-off中切换即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接