Error connecting to Oracle database (ORA-12560) - vb.net

I'm hitting the error mentioned in the Title when attempting to connect to the database in the VB.net application I'm developing. I know it's not the listener or any service issue, as I'm able to connect to the same database, with the same credentials in a different application I developed (I ran that application after failing to connect with the one I'm developing, so it's not the Windows Event log).
Both use an Oracle.DataAccess.Client.OracleConnection to reference an existing ODBC connection. The connections are created and opened in slightly different ways so I figure it's something in my VB code that's causing the issue, but I can't for the life of me think of what it might be.
The non-functional code:
Public Function EstablishCon(ByVal odbc As String,
ByVal uname As String,
ByVal pass As String) As Oracle.DataAccess.Client.OracleConnection
'
Dim constr As String
Dim scon As Oracle.DataAccess.Client.OracleConnection = Nothing
Try
constr = "Data Source=" & odbc & ";User Id=" & uname & ";Password=" & pass & ";"
scon = New Oracle.DataAccess.Client.OracleConnection(constr)
scon.Open()
Catch ex As Exception
MsgBox("Encountered an error while creating the Oracle connection string and opening the connection. This will cause the application to be unable to access any data." _
& " As such the application will close following the closure of this error message." & Chr(10) & Chr(10) & "Error Details: " & ex.Message, vbOKOnly, _
"Critical Error: Failed to the Oracle Database")
scon.ConnectionString = Nothing
End Try
Return scon
End Function
Whereas my working code looks like:
Private Sub MainWin_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'
'Dim scmd As New SqlClient.SqlCommand
Dim QTxt As String = ""
Dim ConStr As String = "Data Source=existing ODBC connection name;User Id=user_name;Password=pass;"
Dim scon As New Oracle.DataAccess.Client.OracleConnection(ConStr)
Dim d As New DataStore
Dim scmd As New Oracle.DataAccess.Client.OracleCommand
Dim odr As Oracle.DataAccess.Client.OracleDataReader
'Setup the datatable in d
Try
d.DT.Columns.Add("App_Type")
d.DT.Columns("App_Type").DataType = GetType(String)
d.DT.Columns.Add("CPU_Seconds")
d.DT.Columns("CPU_Seconds").DataType = GetType(Double)
'd.DT.Columns.Add("Pct_Of_CPU")
'd.DT.Columns("Pct_Of_CPU").DataType = GetType(Double)
d.DT.Columns.Add("RunDate")
d.DT.Columns("RunDate").DataType = GetType(Date)
Catch ex As Exception
Me.Errors.Text = "Encountered an error setting up the data table that will receive the query data. Details: " & ex.Message
d = Nothing
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
Me.Status.Text = Now() & " - Building the SQL executor"
Me.Refresh()
'Build the query executor
Try
scmd.CommandType = CommandType.Text
scmd.Connection = scon
'Capture the query text
QTxt = 'Some text that makes a valid query
scmd.CommandText = QTxt
Catch ex As Exception
Me.Errors.Text = "An error occurred while building the SQL Executor. Details: " & ex.Message & Chr(10) & Chr(10) & Me.Errors.Text
d = Nothing
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
Me.ProgBar.Step = 5
Me.ProgBar.PerformStep()
Me.Status.Text = Now() & " - Connecting to the database" & Chr(10) & Me.Status.Text
Me.Refresh()
Try
'Open the connection
scon.Open()
Catch ex As Exception
Me.Errors.Text = "An error occurred while opening the SQL connection. Details: " & ex.Message & Chr(10) & Chr(10) & Me.Errors.Text
d = Nothing
scon.Close()
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
'Some more stuff that's not relevant
End Sub
Sorry for the messy formatting, I spent 15 minutes trying to keep the two blocks of code separate, but StackOverflow just wasn't having it.
So the only real difference between the two is that one filled in the connection string when declaring the Connection variable, and the other does so later and in a separate function. The function aspect doesn't appear to factor as the error is thrown and caught inside the function. I

So the problem was how I was invoking the form that calls for the function. I had use .Show rather than .ShowDialog.
This resulted in the form variables (which hold the values that get passed in as odbc, uname, & pass) being cleared prior to hitting the Shown event (where the connection function is invoked).

Related

OleDb exception System.Data.OleDb.OleDbException (0x80004005): System resource exceeded

VB2013: I am getting the exception System.Data.OleDb.OleDbException (0x80004005): System resource exceeded. When I query an MS Access database.
Here is what I do in my code:
'Make the connection to connDB
Public connDB As OleDbConnection
connDB = New OleDbConnection
With connDB
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DbFile & ";Persist Security Info=True;Jet OLEDB:Database Password=xxxxxx;"
.Open()
End With
'iterate through some 2500 obects. each object has a set of codes and we will get their description here
GetSysDefinitions (list of codes for an object)
'Close the connection to connDB;
Public Function GetSysDefinitions(sysCodes As List(Of String)) As String
Try
'check to see if the db is available
If connDB Is Nothing Then Return ""
'set up the SQL to get the System Codes and Definitions
Dim sCodes As String = "'" & String.Join("', '", sysCodes) & "'"
Dim sql As String = "SELECT * " & _
"FROM SYS_Codes " & _
"WHERE CODE IN(" & sCodes & ") ; "
Dim daLs As New OleDbDataAdapter(sql, connDB)
Dim dsLs As New DataSet
Dim dtLs As New DataTable
daLs.SelectCommand.CommandTimeout = 60 '60 seconds for the command to timeout
daLs.Fill(dsLs, "Sys") '<=== Exception here at some point
dtLs = dsLs.Tables(0)
'do something with records returned
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Function
This all works great. At some point however I get the exception System.Data.OleDb.OleDbException (0x80004005): System resource exceeded at the line daLs.Fill. I just am not sure why resources are being exceeded and what I need to do to avoid this exception. Seems like I make one connection and then use it to make many queries. Should work right?
Thanks Çöđěxěŕ and Andrew Morton. Dont remeber where I got the code snippet but have been using it for years. I guess the difference is this time Im using that routine in a large number of calls. here is my updated code which I tested and no exceptions:
Using daLs As New OleDbDataAdapter(sql, connDb)
Using dtLs As New DataTable
'fill in the DataTable
daLs.Fill(dtLs)
dtLs.TableName = "CoreSys"
'check for how many rows were returned
'parse out rows
End Using
End Using

Windows Mobile v 6.5 connecting to SQL Server 2008 R2

I have a problem connecting my windows mobile application developed using vb.net in my SQL server 2008 as my back end. Here is my connection string :
Data Source=STEPH-PC\SQL2008;Initial Catalog= MyDB; User ID = myusername; Password = mypassword;
It always give me an error that SQL server does not exist or access denied. Any help on how to solve this issue?
1- Testing connection Server versus Pocket PC:
First at all test if your SQL Server CE mobile agent connects to SQL Server CE Server agent. To do this you have to install SQL Server CE 3.5 in the server and in your Pocket PC. Search in google How to install SQL Server CE 3.5. In the process you create a Virtual Directory in Server and in that directory you got a file sqlcesa35.dll, so to test the connection in your Pocket PC browser write: http://ipserver/virtual_directory/sqlcesa35.dll (of course ipserver must be your server IP and virtual_directory must be your virtual directory name). Doing this you have to get in your Pocket PC the message:
Microsoft SQL Server Compact
Server Agent
At this point I have to mention that always you must have internet connection.
2- Retrieving files from the server (this is a sample code, not debugged, I only have taken some parts from other project and put them here).
Function get_companies(ByVal sSucursal As String, ByVal cn_Interface As System.Data.SqlServerCe.SqlCeConnection, _
ByVal cmd_Interface As System.Data.SqlServerCe.SqlCeCommand, ByVal dr_Interface As System.Data.SqlServerCe.SqlCeDataReader) As Boolean
get_companies = False
Dim _strRemoteConnect As String
Dim _strLocalConnect As String
Dim _strInternetURL As String = sInternetURL
'The last variable sInternetURL is something like: http://ip_server/virtual_directory/sqlcesa35.dll
_strRemoteConnect = "Provider=SQLOLEDB;Data Source=" & sIPSQLServer & ";Initial Catalog=" & sBDSQLServer & ";User Id=" & sUserSQLServer & ";Password=" & sClaveSQLServer
'sIPSQLServer is the server ip where is running SQL Server
'sBDSQLServer is your DataBase server.
_strLocalConnect = "Data Source=" & sPath & "\" & sDataBase_Interface & "; Password=" & sPassword
'sPath is your directory in your Pocket PC, begings with \
'sDataBase_Interface is the database in my Pocket PC, an .sdf file
Dim rda As System.Data.SqlServerCe.SqlCeRemoteDataAccess = New System.Data.SqlServerCe.SqlCeRemoteDataAccess
rda.InternetLogin = sUserInternet 'a valid user in your domain
rda.InternetPassword = sClaveInternet
rda.InternetUrl = _strInternetURL
rda.LocalConnectionString = _strLocalConnect
Do While True
Try
'In server database there is a table: Monedas
rda.Pull("_Monedas", "Select Moneda, Descripcion, Abreviada From Monedas Where Sucursal = '" & sSucursal & "'", _
_strRemoteConnect, System.Data.SqlServerCe.RdaTrackOption.TrackingOff)
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Loop
'read the data received, just testing, may be this code not to be here because you process the data outside the function.
Try
cmd_Interface.CommandText = "Select Moneda, Descripcion, Abreviada From _Monedas"
dr_Interface = cmd_Interface.ExecuteReader()
Do While dr_Interface.Read()
messagebox.show("Moneda = " & dr_interface("Moneda") & " - " & dr_interface("Descripcion") & " - " & dr_interface("Abreviada"), _
"Currencies Received", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
Loop
get_companies = true
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
Finally
'If cn_Interface.State <> ConnectionState.Closed Then
' cmd_Interface.Dispose()
' cn_Interface.Close()
' cn_Interface.Dispose()
'End If
End Try
End Function
3- Excecuting a sentence in Database Server from your Pocket PC and Transferring data from Pocket to Server:
Function EnviarClientesNuevos(ByVal sSucursal As String, ByVal sZona As String, ByVal sRuta As String) As Boolean
Dim sLineas As String
Dim nRegs As Integer
Dim cn_Interface As System.Data.SqlServerCe.SqlCeConnection
Dim cmd_Interface As System.Data.SqlServerCe.SqlCeCommand
EnviarClientesNuevos = False
Dim _strRemoteConnect As String
Dim _strLocalConnect As String
Dim _strInternetURL As String = sInternetURL
_strRemoteConnect = "Provider=SQLOLEDB;Data Source=" & sIPSQLServer & ";Initial Catalog=" & sBDSQLServer & ";User Id=" & sUserSQLServer & ";Password=" & sClaveSQLServer
_strLocalConnect = "Data Source=" & sPath & "\" & sDataBase_Interface & "; Password=" & sPassword
Dim rda As System.Data.SqlServerCe.SqlCeRemoteDataAccess = New System.Data.SqlServerCe.SqlCeRemoteDataAccess
rda.InternetLogin = sUserInternet
rda.InternetPassword = sClaveInternet
rda.InternetUrl = _strInternetURL
rda.LocalConnectionString = _strLocalConnect
Do While True
If DropTableE("_NEW_CLIENTES_XX") Then
Try
'_NEW_CLIENTES_XX is a table in your SQL Server (The server, not the Pocket)
rda.Pull("_NEW_CLIENTES_XX", "Select Id, Sucursal, Zona, CodCli, Nombre, Direccion, Ruc, Clase, Ruta " & _
"FROM _NEW_CLIENTES_XX WHERE Sucursal = ''", _strRemoteConnect, SqlServerCe.RdaTrackOption.TrackingOn)
'In where clause I compare to '' because I only need the structure
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Function
End Try
End If
Loop
Try
'--
cn_Interface = New System.Data.SqlServerCe.SqlCeConnection
cn_Interface.ConnectionString = "Data Source=" & sPath & "\" & sDataBase_Interface & ";Password=" & sPassword
cn_Interface.Open()
cmd_Interface = cn_Interface.CreateCommand()
cmd_Interface.CommandType = CommandType.Text
'--
'here I have an open connection to another database in my Mobile Device. Here I have to mention that I work with 2 databases in my mobile device:
'One database for getting the data from server, I only use it when I get data from server and when I send data to server
'and other database which is my main database, the database that is used all the day storing customers transactions.
'here I already have open (outside this function) the connection to this second database, but the sentence are the same above,
'something like this:
'Try
' cn = New System.Data.SqlServerCe.SqlCeConnection
' cn.ConnectionString = "Data Source=" & sPath & "\" & sDataBase_Ppal & ";Password=" & sPassword
' cn.Open()
' cmd = cn.CreateCommand()
' cmd.CommandType = CommandType.Text
'Read the data from my main Pocket PC database
cmd.CommandText = "SELECT CodCli, Nombre, Direccion, Ruc, Clase From CLIENTES WHERE CLASE IN ('N', 'M')"
dr = cmd.ExecuteReader()
Do While dr.Read()
'Insert the data in the table structure that I get above.
'remember that this table is in the database that only is used when transferring data, its a temporal database.
cmd_Interface.CommandText = "INSERT INTO _NEW_CLIENTES_XX (Sucursal, Zona, CodCli, Nombre, Direccion, Ruc, Clase, Ruta) " & _
"VALUES('" & sSucursal & "', '" & sZona & "', " & dr("CodCli") & ", '" & _
dr("Nombre") & "', '" & dr("Direccion") & "', '" & dr("Ruc") & "', '" & _
dr("Clase") & "', '" & sRuta & "')"
nRegs = cmd_Interface.ExecuteNonQuery()
Loop
dr.Close() : dr.Dispose()
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
Exit Function
Finally
Try
dr.Close()
dr.Dispose()
Catch ex As Exception
End Try
'If cn.State <> ConnectionState.Closed Then
' cmd.Dispose()
' cn.Close()
' cn.Dispose()
'End If
If cn_Interface.State <> ConnectionState.Closed Then
cmd_Interface.Dispose()
cn_Interface.Close()
cn_Interface.Dispose()
End If
End Try
Do While True
Try
'I excecute a sentence in the Server. I delete the data in _NEW_CLIENTES_XX which is a work table in SQL server.
rda.SubmitSql("Delete From _NEW_CLIENTES_XX Where Sucursal = '" & sSucursal & "' AND Zona = '" & sZona & "' And Ruta = '" & sRuta & "'", _strRemoteConnect)
'I send the data to server
rda.Push("_NEW_CLIENTES_XX", _strRemoteConnect, System.Data.SqlServerCe.RdaBatchOption.BatchingOn)
EnviarClientesNuevos = True
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Function
End Try
Loop
End Function
Generalities:
Function DropTableP(ByVal sTabla As String) As Boolean
'Dim cn_Interface As System.Data.SqlServerCe.SqlCeConnection
'Dim cmd_Interface As System.Data.SqlServerCe.SqlCeCommand
'Dim dr_Interface As System.Data.SqlServerCe.SqlCeDataReader
Dim nRegs As Integer
Try
'cn_Interface = New System.Data.SqlServerCe.SqlCeConnection("Data Source=" & sPath & "\" & sDataBase_Ppal & "; Password=" & sPassword)
'cn_Interface.Open()
'cmd_Interface = cn_Interface.CreateCommand()
'cmd_Interface.CommandType = CommandType.Text
cmd.CommandText = "Select TABLE_NAME From INFORMATION_SCHEMA.TABLES Where TABLE_NAME = '" & sTabla & "'"
dr = cmd.ExecuteReader()
If dr.Read() Then
dr.Close()
dr.Dispose()
cmd.CommandText = "DROP TABLE " & sTabla
nRegs = cmd.ExecuteNonQuery()
DropTableP = True
Else
dr.Close()
dr.Dispose()
DropTableP = True
End If
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'If cn_Interface.State <> ConnectionState.Closed Then
' cn_Interface.Close()
' cn_Interface.Dispose()
'End If
End Try
End Function
Sub ShowErrorSqlServerCE(ByVal exc As System.Data.SqlServerCe.SqlCeException)
Dim bld As New System.Text.StringBuilder
Dim err As System.Data.SqlServerCe.SqlCeError
Dim errorCollection As System.Data.SqlServerCe.SqlCeErrorCollection = exc.Errors
Dim errPar As String
Dim numPar As Integer
' Loop through all of the errors.
For Each err In errorCollection
bld.Append(ControlChars.Cr & " Error Code: " & err.HResult.ToString("X"))
bld.Append(ControlChars.Cr & " Message : " & err.Message)
bld.Append(ControlChars.Cr & " Minor Err.: " & err.NativeError)
bld.Append(ControlChars.Cr & " Source : " & err.Source)
' Loop through all of the numeric parameters for this specific error.
For Each numPar In err.NumericErrorParameters
If numPar <> 0 Then
bld.Append(ControlChars.Cr & " Num. Par. : " & numPar.ToString())
End If
Next numPar
' Loop through all of the error parameters for this specific error.
For Each errPar In err.ErrorParameters
If errPar <> [String].Empty Then
bld.Append(ControlChars.Cr & " Err. Par. : " & errPar)
End If
Next errPar
' Finally, display this error.
MessageBox.Show(bld.ToString(), "SQL Server CE")
' Empty the string so that it can be used again.
bld.Remove(0, bld.Length)
Next err
End Sub
As I said above: the code that I put here needs to be debugged...I have only extracted some parts from my project and put here. Hope this will help you!

SQL Server 2012 Express connection successful but error occured during login

I get the following errors accessing my local SQL Server 2012 Express data using VB.Net 2012.
A connection was successfully established with the server, but then an error occurred during the login process. (provider: TCP Provider, error: 0 - The specified network name is no longer available.
A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
It seems like the connection is not being released because I have a function with the exact same code (except parameters) and it works 3 times, but on the 4th I get an error like above.
Code:
Public Function LookupSQRIDX(Lotnumber As String, TableToUse As String, IDXFieldToUse As String, LotField As String, LotMatch As String, SearchLine As String) As String
Dim sConnection As String = "Server=MARIO\VSQL;Database=LEASE;User Id=cookieuser;Password=oreo;"
Dim objCommand As New SqlCommand
objCommand.CommandText = "Select top 1 " & IDXFieldToUse & " From [dbo].[" & TableToUse & "] where " & LotField & " like '%" & LotMatch & "' and line = '" & SearchLine & "' order by " & IDXFieldToUse
objCommand.Connection = New SqlConnection(sConnection)
objCommand.Connection.Open()
Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()
Try
Dim NumCols, NumRows As Integer
Dim RowNum As Integer
Dim MyArray = ""
Dim Map1LastLot = "", Map2LastLot = ""
If objDataReader.HasRows Then
NumCols = objDataReader.FieldCount - 1
Do While objDataReader.Read()
RowNum = RowNum + 1
MyArray = objDataReader(0).ToString
Loop
NumRows = RowNum
objDataReader.Close()
objCommand.Dispose()
Return MyArray
Else
objDataReader.Close()
objCommand.Dispose()
Return ""
End If
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message)
objDataReader.Close()
objCommand.Dispose()
Return ""
End Try
objDataReader.Close()
objCommand.Dispose()
End Function
Added the following (using the tip provided by hvd) and the problem went away. Evidently you need to close and dispose of the connection even though it is already contained in the objCommand being disposed.
objCommand.Connection.Close()
objCommand.Connection.Dispose()
objDataReader.Close()
objCommand.Dispose()

VB Custom login page. Incorrect syntax near '.'.

I am creating a custom log in page using VB in Visual Studio. Every time I try logging in, however, I get the following error:
"Incorrect syntax near '.'".
When I put in the wrong username/password combo it recognizes this, but when it is right it will get this error and fail to log in.
Private Function VerifyLogin(ByVal UserName As String) As Boolean
Try
Dim cnn As New Data.SqlClient.SqlConnection
cnn.ConnectionString = My.MySettings.Default.RedwoodConnectionString.Replace(";Integrated Security=True", ";Integrated Security=False") & UserSetting
Dim cmd As New Data.SqlClient.SqlCommand
cmd.Connection = cnn
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT COUNT (principal_id) FROM _ sys.database_principals WHERE(name = '" & UserName & "')"
cnn.Open()
Dim i As Integer
i = cmd.ExecuteScalar()
cnn.Close()
If (i > 0) Then Return True
Return False
Catch ex As Exception
System.Windows.Forms.MessageBox.Show("Error: " & ex.Message & vbNewLine & "Location: VerifyLogin() in Login.vb" & vbNewLine & "Returned value: False")
Return False
End Try
End Function
Look at this portion of your sql:
FROM _ sys.database_principals
See the mistake there? It thinks the _ is the full table name and sys is an alias. At this point, .database_principals is no longer valid, hence your error.
And while we're at it, you really need to fix the sql injection vulnerability!!

OleDB Exception: Could not find installable ISAM

Dim con As New OleDb.OleDbConnection
Sub connecttodatabase(ByVal fileselected As String)
Dim databasepassword
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = " & fileselected
Try
con.Open()
Catch e As OleDb.OleDbException
If e.Message = "Not a valid password." Then
Console.WriteLine("Database has a password. Please enter password to continue.")
databasepassword = Console.ReadLine()
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = " & fileselected & ";JetOLEDB:Database Password=" & databasepassword & ";"
con.Open()
End If
errorid = 1
Finally
End Try
End Sub
The error I am encountering occurs at the second con.Open() when I try to connect to a .mdb database file which I created in access, the function correctly tells me I have a password, but then once I enter my password I get the error defined in the title, and I have no idea why. Any help would be greatly appreciated.
Try this instead:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=YOURPASS;
Also, what exception are you getting from the first call to open the db? Maybe it's same problem: the ISAM isn't present. Try reinstalling MDAC:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=78cac895-efc2-4f8e-a9e0-3a1afbd5922e