How to test SqlServer connection without opening a database

前提是你 提交于 2019-12-10 14:57:48

问题


The title pretty much says it all. I want to create a SqlConnection and then check that connection without opening a database, cause at that point I don't know yet where will I connect to. Is it possible to do that? The SqlConnection class has a 'Open' member which tries to open the database you'd set in the Database property, and if you didn't set one, SqlServer tries with the master db. The thing is the user I'm trying to connect with (MACHINE\ASPNET) has access to some databases (which I don't know yet) and not the master db.

Regards, Seba


回答1:


Connect to temp db. Everybody has accecss to tempdb so you will be able to authenticate yourself for access. Later when you know the actual database , you can change this property to connect to the db you want.




回答2:


I am not sure if this is what you need.

Check if a user has access to a database in Sql Server 2005

SELECT HAS_DBACCESS('Northwind');

HAS_DBACCESS returns information about whether the user has access to the specified database (BOL).

Find all databases that the current user has access to

SELECT [Name] as DatabaseName from master.dbo.sysdatabases
WHERE ISNULL(HAS_DBACCESS ([Name]),0)=1
ORDER BY [Name]



回答3:


If you need to know only if the service is active, you could try to connet via a socket to the port, to see if it is open




回答4:


Just curious... What information will you be able to verify if you don't know the precise database you need to connect to? Many things that could go wrong with the "real" database would be untestable from this sort of test connection, such as connectivity or security.




回答5:


I don't know whether you got your answers but as we all look here for answers I hope this is what you were looking for

dim con as new sqlconnection
con.connectionstring="<<put your conn string here>>"
'try...catch block fires exception if the con is not successfully opened
try
con.open()
catch ex as exception
msgbox ex.message
end try


来源:https://stackoverflow.com/questions/154485/how-to-test-sqlserver-connection-without-opening-a-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!