How to test SqlServer connection without opening a database
Asked Answered
R

5

6

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

Renown answered 30/9, 2008 at 19:8 Comment(1)
So, if I understand you correctly, are you trying to get the list of databases for which the aspnet user has access to?Junction
A
11

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.

Amaryl answered 30/9, 2008 at 21:9 Comment(0)
J
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]
Junction answered 30/9, 2008 at 19:19 Comment(0)
P
1

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

Protrude answered 30/9, 2008 at 21:25 Comment(0)
I
0

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.

Incapable answered 30/9, 2008 at 19:13 Comment(1)
well... I just wanna know if the user can authenticate against the SqlServer, thus, it is a valid server and a valid login in that server... I guess the answer is NO you can'tRenown
H
-1

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
Hydrocephalus answered 26/11, 2011 at 3:58 Comment(1)
I don't think you understood the question... that's exactly my point and Lerning's answer is the key to my problem Everybody has accecss to tempdbRenown

© 2022 - 2024 — McMap. All rights reserved.