English 中文(简体)
记录NHibernate SQL查询
原标题:Logging NHibernate SQL queries

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

我可以使用log4net来记录SQL查询:

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

然而,我想找到一种方法来从代码中记录SQL查询。这样,我将记录在try / catch语句中引发异常的特定SQL查询。

现在,当异常发生时,我必须对SQLFileLog进行数据挖掘,以查找导致异常的查询,这并不高效。

问题回答

你可以使用拦截器来实现这个功能。

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

        return sql;
    }
}

详见NHibernate文档(Webarchive)中关于使用不同方式在NHibernate中注册它的说明。

您可以覆盖驱动程序:

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>();

要么使用SQL Profiler,要么查看nhprof:http://nhprof.com/

两种方法都可以让你看到 SQL 输出。

在 Hibernate 配置文件中设置 show_sql 属性。

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

使用具有特定目标的log4net appender(记得它支持开/关切换),或者只是扩展它并在try-catch-finally-off内进行开/关切换。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签