DSN-less connection to SQL server in VB.NET - vb.net

Tried seemingly everything here to get this to work but I keep getting "Keyword not supported" errors for just about every iteration of dsn-less connection strings I can find out there in internet land, two are shown below.
Public cnSystem As New SqlClient.SqlConnection
Public Sub ConnectToSQL()
Dim sConnectionString As String
Dim sServer As String
Try
'Always connect to production server to get startup environment variables
If gbIsProduction Then
If gsProductionServer = "" Then
sServer = "xxxxx-SQL"
Else : sServer = gsProductionServer
End If
Else : sServer = gsDevelopmentServer
End If
//Doesn't work
sConnectionString = "Network Library=DBMSSOCN;Data Source=xxxxx-SQL,1433;Inital Catalog=xxxxx;User ID=sa;Password=xxxxx;"
//Doesn't work
sConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;UserId=sa;Initial Catalog=xxxxx;Data Source=xxxxx-SQL;Password=xxxxx;"
cnSystem.ConnectionString = sConnectionString
cnSystem.Open()
cmdSystem.Connection = cnSystem
Catch ex As Exception
RaiseError("", "modGeneral." & System.Reflection.MethodBase.GetCurrentMethod().Name, Err.Number, Err.Description)
End Try
End Sub
Any ideas on what is the proper connection string for a DSN-less connection to a SQL server using the data objects I am using?
Thanks!

While not the exact answer, this website helps me all the time:
http://www.connectionstrings.com/
Also, when using System.Data.SQLClient you do not have to specify the provider and I believe you will get the error you are receiving. Remove that part.

try creating a udl file to create your connection string. then you can test it to ensure it is working - http://www.codeasp.net/blogs/hajan/microsoft-net/857/working-with-udl-universal-data-link-files

Related

Need some help diagnosing SEHException External component has thrown an exception

Windows Forms application using VB.Net and VS2012. Connecting to an Access database using Access Runtime 2013. The app is compiled to target x86. The problem is intermittent and occurs on multiple different PC's randomly, and accessing a database on a local hard drive.
Using cn As New OleDbConnection
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
If Not OpenDBConnection(cn) Then
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
MsgBox("Unable to make database connection to update screen status.", MsgBoxStyle.OkOnly, "Database Connection Error (MMUN1)")
Exit Sub
End If
'continue processing....
end using
Public Function OpenAccessConnection(ByRef conn As OleDb.OleDbConnection) As Boolean
Dim builder As New OleDbConnectionStringBuilder()
'conn.Provider = "Microsoft.ACE.OLEDB.12.0"
Try
builder.ConnectionString = "Data Source=" & DPATH & DBNAME
builder.Add("Provider", "Microsoft.ACE.OLEDB." & ACCESSVER & ".0") 'ACCESSVER is '12'
conn.ConnectionString = builder.ConnectionString
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
conn.Open()
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
Return True
Catch ex As Exception
MsgBox("Unable to make Access connection. Error# " & Err.Number & " " & ErrorToString() & " " & ex.ToString, MsgBoxStyle.OkOnly, "Database Connection Error (OLEOPN1)")
Return False
Finally
builder.Clear()
builder = Nothing
End Try
End Function
Public Function OpenDBConnection(ByRef conn As OleDbConnection) As Boolean
'I know this is an extraneous function call but it is in transition from multiple prior uses and I thought I had better not exclude it from this post in case it mattered for some reason
OpenDBConnection = OpenAccessConnection(conn)
End Function
Error being returned intermittently:
I have read many of the posts on this topic and have not found a solution, and frankly am not sure where to look. Could this be coming from an earlier application error? Thread/STA issue? If so, what do I do about it? On the development machine, I will on occasion see a DisconnectedContext error, but have not seen the External component error which appears on PC's running the released version. Are these related? Also, there are some ADO (ADODB) connections being made to the database (still trying to replace/upgrade), but these are not open at the time this new connection is being made. But could it be a connection pooling issue? Thanks in advance for any help out there.

How to load data from oracle database using .dsn? (VB.NET)

I'm trying to test if the connection from my utility to oracle DB is working by using .dsn . I've searched from many forums but to no avail . Here is my code:
Dim filedsn As String = "C:\my_dsn.dsn"
Dim uid As String = "id123"
Dim pwd As String = "1234"
Dim cn As OdbcConnection
cn = New OdbcConnection("Driver=Oracle in OraClient11g_home2;Provider=msdaora;dsn=" & filedsn & ";uid=" & uid & ";pwd=" & pwd & ";")
Dim mystring As String = "Select * from DD_CADS1.PDTABLE_12_1001"
Dim cmd As OdbcCommand = New OdbcCommand(mystring)
cn.Open()
MsgBox("Connected")
cn.Close()
But these error appears..
ERROR [HY000] [Oracle][ODBC][Ora]ORA-12560: TNS:protocol adapter error
ERROR [IM006] [Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed
ERROR [HY000] [Oracle][ODBC][Ora]ORA-12560: TNS:protocol adapter error
Can you tell me what's the problem with my codes? Is there any other way to connect to oracle database through .dsn using VB.net? I'm currently using ** Oracle 11g**.
The biggest problem in your code is that you use ODBC to connect to Oracle. You should use ODP.NET, which is even recommended by Microsoft. What you doing is there [most likely] for backwards compatibility and not to write the new stuff.
Here your problem is in connection string, which should look like this
"DSN=oracledsn;UID=myUID;PWD=myPWD;Integrated Security=no;"
And you don't need command just to test connection
using cn= New OdbcConnection(".....")
cn.Open()
if cn.State = ConnState.Open Then MessageBox.Show(...)
end using
When you use using it will take care of closing and disposing of connection.

Else Portion of Code keeps timing out

I have a code to check the connection between access and sql server upon opening the form. If there is a connection a message box pops up and says so. If not there is supposed to be a message box indicating there is no connection. Instead I get the error:
Run Time Error '-2147467259 (80004005)':
[DBNETLIB][ConnectionOpen (Connect()).]Specified SQL Server Not Found
Which is not what I am wanting it to do, is it something in my coding or is there no way to get this to work?
Public Sub AutoExec()
Dim cnn As ADODB.Connection
Dim localrst As New ADODB.Recordset
Dim remoterst As New ADODB.Recordset
Set cnn = New ADODB.Connection
cnn.Open "Provider=SQLOLEDB; Data Source=DB; Initial Catalog=HRLearnDev;" _
& "User Id=ID; Password=PW;"
If cnn.State = adStateOpen Then
MsgBox ("You have an established connection with the L&TD SQL Server Database.")
Else
MsgBox ("Cannot connect to remote server. Data will be stored locally to CDData Table until application is opened again.")
End If
cnn.Close
End Sub
In situations like these, you typically want to use an On Error GoTo construct - then send the code to your error handler if an error occurs (you can test to make sure the error number is what you expect with Err.Num).
However, in your case it may be even easier to use On Error Resume Next. This tells the interpreter "If an error occurs, go to the next line. I will figure out what went wrong and deal with it."
You usually do this when you have a single function call that either produces an error or a sensible value. I often do something like this:
On Error Resume Next
returnValue = -1
returnValue = functionThatReturnsPositiveValue()
If returnValue < 0 Then
MsgBox "oops - the function failed!"
Else
' <<<< do whatever needs doing >>>>
End If
In your case that's almost exactly what you would do. Complete example:
Public Sub AutoExec()
Dim cnn As ADODB.Connection
Dim localrst As New ADODB.Recordset
Dim remoterst As New ADODB.Recordset
On Error Resume Next ' <<<<<< add this line so an error doesn't stop the code
Set cnn = New ADODB.Connection
cnn.State = 0 ' <<<<< not sure if you need something like this, or if the New command
already set it to some sensible value other than "adStateOpen"
cnn.Open "Provider=SQLOLEDB; Data Source=DB; Initial Catalog=HRLearnDev;" _
& "User Id=ID; Password=PW;"
If cnn.State = adStateOpen Then ' <<<<<< this will only be true if no error occurred
MsgBox ("You have an established connection with the L&TD SQL Server Database.")
Else
MsgBox ("Cannot connect to remote server. Data will be stored locally to CDData Table until application is opened again.")
End If
On Error GoTo 0 ' <<<<<<<< turn off error handling - we have passed the "tricky" spot.
' <<<<<< lots more code goes here >>>>>>
If cnn.State = adStateOpen Then cnn.Close ' <<<<<<<< only close connection if it was open!!
End Sub

Keyword not supported: 'failover partner:sql-failover;initial catalog' in VB.NET

We have a SQL Server configured for mirroring. The initial server failed today and almost all our applications failed over correctly except for a VB.NET application.
When it starts up to set the connection string I get the following error:
"Keyword not supported: 'failover partner:sql-failover;initial catalog'."
Here is the code to connect:
Dim sConnectionString As String
Dim sServer As String
Try
'Always connect to production server to get startup environment variables
If gbIsProduction Then
If gsProductionServer = "" Then
sServer = "PROD-SQL"
Else : sServer = gsProductionServer
End If
Else : sServer = gsDevelopmentServer
End If
sConnectionString = "Data Source=" & sServer & ";Failover Partner:SQL-FAILOVER;Initial Catalog=*****;User ID=****;Password=******;"
cnSystem.ConnectionString = sConnectionString
cnSystem.Open()
cmdSystem.Connection = cnSystem
Catch ex As Exception
RaiseError("", "modGeneral." & System.Reflection.MethodBase.GetCurrentMethod().Name, Err.Number, Err.Description)
Any reason why? I know Failover Partner is not supported in .NET 1.1 but I am using framework 3.5 SP1.
Thanks!
This part of the connection string is wrong
....;Failover Partner:SQL-FAILOVER;.....
should be
....;Failover Partner=SQL-FAILOVER;......

properly closing adodb connections in vb.net

in vb.net, there are some applications that use adodb to access a mysql server.
private adoconnect as new adodb.connection
public adors as new adodb.recordset
public function returnadors(byval column as string) as string
return adors.fields(column).value.tostring
end function
Public Function ReadData(ByVal strQuery As String, Optional ByVal strWhere As String = vbNullString) As Boolean
Try
If ADOConnect.State = ConnectionState.Open Then Call CloseConnection()
ADOConnect.Open(dsn, user, pass)
ADORS.Open(strQuery, ADOConnect, ADODB.CursorTypeEnum.adOpenDynamic)
If not ADORS.EOF Then Return True
Catch ex As Exception
msgbox(ex)
End Try
Return False
End Function
public sub closeconnection()
if adoconnect.state = connectionstate.open then adoconnect.close
end sub
now lets say we wanted to populate a textbox with something from the database:
if readdata("SELECT NAME FROM USERS WHERE ID = 1") then
me.textbox1.text = returnadors("NAME")
end if
call closeconnection
re writing these functions is a big task - and I am not interested in doing it unless absolutely needed.
Here is my problem though.
even if the connection is closed (and i have stepped through the code, it closes)
The connection is still visible on the sql server in a sleep state
why? and how can i make sure that the connection is closed.
thanks
Add the following to your ConnectionString:
Pooling=False;
I don't have much experience with exactly what you are doing, but this is usually the path I take with sqlserver connections. Using will automatically close your connection.
Using ADOconnect
'operations
End Using