使用NHibernate测试连接参数 [英] Testing Connection Parameters with NHibernate
问题描述
我们有一个程序,用户可以在其中指定其数据库连接参数。通常的嫌疑犯包括主机,端口,用户名,密码和表名称。我们使用NHibernate连接到数据库。我们想要做的是能够使用NHibernate构建配置,然后在继续其他操作之前测试连接参数;这是可能通过NHibernate,或将需要使用我们支持的特定驱动程序和创建自定义TestConnection()方法的每个数据库类型每个类型?
我意识到这是一个老帖子 - 但我想一个问题的答案从来没有伤害。 >
我不认为有明确告诉NHibernate测试连接字符串的方法。但是,当实例化SessionFactory时,它将尝试连接到数据库。
我使用Fluent NHibernate,但我相信下面的例子仍然会解释为什么情况。
Dim sf as SessionFactory
Try
sf = CreateSessionFactory()
Catch ex as FluentNHibernate.Cfg.FluentConfigurationException
Messagebox.Show(ex.InnerException.Message)
结束尝试
ex.InnerException.Message
包含实际错误,并会告诉您是否:
- 连接字符串无效
- 找不到服务器
- 无法验证用户/密码
We have a program where users can specify their database connection parameters. The usual suspects including host, port, username, password, and table name. We are connecting to the database using NHibernate. What we'd like to do is be able to build the configuration with NHibernate and then test the connection parameters before continuing with other operations; notifying the user of failure.
Is this possible to do through NHibernate, or will it require using each database type we support's specific driver and creating a custom TestConnection() method for each type?
I realize this is an old post - but I guess an answer to a question never hurts.
I don't think there is a way to explicitly tell NHibernate to test out the connection string. However, when you instantiate the SessionFactory it will attempt to connect to the database. You could wrap your SessionFactory creation in a Try/Catch and handle the error that way.
I use Fluent NHibernate, but I'm sure the following example will still explain the situation.
Dim sf as SessionFactory
Try
sf = CreateSessionFactory()
Catch ex as FluentNHibernate.Cfg.FluentConfigurationException
Messagebox.Show(ex.InnerException.Message)
End Try
The ex.InnerException.Message
contains the actual error and will tell you if:
- The connection string was invalid
- The server could not be found
- The user/pass could not be authenticated
这篇关于使用NHibernate测试连接参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!