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!
Related
I've got a utility function in a much larger project that updates a backend SQL database. It's currently failing most times I use it, with the error:
There is already an open DataReader associated with this Command which must be closed first.
The code for the function is below:
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Try
Dim cmd As New SqlCommand With {
.Connection = conn
}
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
cmd.Dispose()
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
End Try
End Function
I've gone through the rest of the code to make sure that whenever I have a SQLDataReader declared I later call reader.close(). I added the cmd.Dispose() line to this and all the other ExecuteNonQuery functions I could find - incase that helped?
Are there any other instances/types of reader that might not be being closed?
In the case of an Exception, you aren't disposing your command.
If you don't want to use Using, add a Finally
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Dim cmd As SqlCommand
Try
cmd = New SqlCommand With {.Connection = conn}
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
Finally
cmd.Dispose()
End Try
End Function
but Using might be simpler
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Using cmd As New SqlCommand With {.Connection = conn}
Try
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
End Try
End Using
End Function
Can somebody tell me what I've done wrong inside my coding? I am trying to match the user login name and password with the one inside the database. If got row and matched then user will be able to login into the system but it seems like my system can only read the first row of my data table (inside database).
Here is my coding that I currently use.
Private Sub CheckLogin()
Dim lCnn As New SqlConnection
Dim lCmd As New SqlCommand
Dim lRd As SqlDataReader
Dim lsCmd As String
If TextBoxLogin.Text = "" Then
MsgBox("Enter your Username.")
Try
TextBoxLogin.Focus()
Catch ex As Exception
End Try
ElseIf TextBoxPass.Text = "" Then
MsgBox("Enter your Password.")
Try
TextBoxPass.Focus()
Catch ex As Exception
End Try
Else
lCnn.ConnectionString = GetConnString()
lCnn.Open()
lCmd.Connection = lCnn
lsCmd = "SELECT * FROM UserInfo..UserInfo "
lsCmd &= " INNER JOIN UserInfo..UserAccess ON UserLogin = UA_UserLogin "
lsCmd &= " WHERE (UserLogin = " & SQLQuote(Trim(TextBoxLogin.Text)) & " AND UserPassword = " & SQLQuote(Trim(TextBoxPass.Text))
lsCmd &= " AND UserActive = 1"
lsCmd &= " AND UA_AICode = 'MENU')"
lCmd.CommandText = lsCmd
lRd = lCmd.ExecuteReader()
If lRd.HasRows Then
lRd.Read()
lbLoginSuccess = True
gsLoginID = Trim(TextBoxLogin.Text)
gsUserPass = Trim(TextBoxPass.Text)
Me.Close()
Else
lnCurRetry += 1
Alert("Wrong Username or Password.")
End If
lRd.Close()
lCnn.Close()
End If
If Not lbLoginSuccess Then
If lnCurRetry >= 3 Then
Me.Close()
End If
End If
End Sub
I appreciate your help. Thanks.
Your code is not really bad, but can be better if utilize that sintax:
Using LCnn As New SqlConnection
LCnn.ConnectionString = GetConnString()
Try
LCnn.Open()
Using LCmd As New SqlCommand("SELECT * FROM UserInfo " & _
"INNER JOIN UserAccess ON UserLogin = UA_UserLogin " & _
"WHERE (UserLogin = '" & TextBoxLogin.Text.trim & "' " & _
"AND UserPassword = '" & TextBoxPass.Text.Trim & "' " & _
"AND UserActive = 1 AND UA_AICode = 'MENU')", LCnn)
Dim LRdr As SqlDataReader
Try
LRdr = SQL_Cmd.ExecuteReader
If Not SQL_Rdr.HasRows Then
msgbox("Empty Results...")
else
<your code>
endif
catch ex as Exception
msgbox("Error: " & ex.message)
end try
end using ' Lcmd
catch exConn as Exception
msgbox("Error: " & exConn.message)
end try
end using ' LCnn
Remember: the Using/End Using syntax can help you to manage resources. End Using always close and dispose resources.
Good luck
I am developing an application in Visual Basic using Visual Studio 2013. In this application I am attempting to use an oledb UPDATE to write data out to an Excel spreadsheet treated as a database. I have tried numerous different formats of this but I either get a syntax error or it pretends to work but nothing actually gets written to the file. Can anyone tell me what is wrong with this code:
Public Function WriteToExcel(ExcelPath As String, dtUser As DataTable)
Dim vOffice As String = dtUser.Rows(0).Item("Office").ToString
Dim vDivision As String = dtUser.Rows(0).Item("Division").ToString
Dim vSection As String = dtUser.Rows(0).Item("Section").ToString
Dim vUser As String = dtUser.Rows(0).Item("UserID").ToString
Dim ExcelconnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelPath & ";Extended Properties='Excel 12.0 Xml;HDR=YES';"
Dim BatchID As Long = 0
Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice WHERE [Primary User] = #uUser"
'Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice, " & _
'"Division = #uDivision, " & _
'"Section = #uSection " & _
'"WHERE [Primary User] = #uUser"
Using conn As New OleDb.OleDbConnection(ExcelconnString)
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#uOffice", vOffice)
cmd.Parameters.AddWithValue("#uDivision", vDivision)
cmd.Parameters.AddWithValue("#uSection", vSection)
cmd.Parameters.AddWithValue("#uUser", vUser)
Try
MessageBox.Show("Attempting to update " & vUser & ". " & vOffice & ", " & vDivision & ", " & vSection & "!")
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message & vbNewLine & ex.StackTrace)
End Try
End Using
End Function
Your SQL has two issues:
OleDbCommands use question marks ? as the placeholder for parameters, not #parameterName (that's for SqlCommands).
Section is a reserved keyword, so it needs to be escaped: [Section].
I have two seperate INSERT statements that I want to run one after the other,
the first one runs successfully but it seems like it isn't even getting to the second statement any idea why?
Try
con.Open()
cmd.ExecuteNonQuery()
resultSQL.ForeColor = Drawing.Color.Green
resultSQL.Text = "Successfully Saved"
Catch ex As Exception
Response.Write(ex.Message)
resultSQL.ForeColor = Drawing.Color.Red
resultSQL.Text = ex.Message
Finally
End Try
INSERT 2 which is not running:
strQuery = "INSERT INTO [SD_EPOS_Entry]" _
& " ([Trade_Activity_Code] " _
& " VALUES " _
& " (#Trade_Activity_Code1)"
cmd = New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#Trade_Activity_Code1", tcodeVar)
Try
con.Open()
cmd.ExecuteNonQuery()
resultSQL.ForeColor = Drawing.Color.Green
resultSQL.Text = "Successfully Saved2"
Catch ex As Exception
Response.Write(ex.Message)
resultSQL.ForeColor = Drawing.Color.Red
resultSQL.Text = ex.Message
Finally
Right off the bat there seems to be a missing parenthesis in your second query:
strQuery = "INSERT INTO [SD_EPOS_Entry]" _
& " ([Trade_Activity_Code] " _
& " VALUES " _
& " (#Trade_Activity_Code1)"
It should be:
strQuery = "INSERT INTO [SD_EPOS_Entry]" _
& " ([Trade_Activity_Code]) " _
& " VALUES " _
& " (#Trade_Activity_Code1)"
I would also advise for proper disposal of any SqlCommand and SqlConnection instances you create, either by using the Dispose() method or declaring them in a Using statement.
If as you say your second query isn't even reached, follow your code at runtime with a debugger and look at which point it stops. That ougth to provide some clue.
UPDATE:
This should execute both your INSERT statements in a single operation:
strQuery = "INSERT INTO [SD_T_Code]" _
& " ([Trade_Activity_Code]) " _
& " VALUES " _
& " (#Trade_Activity_Code)" _
& ";INSERT INTO [SD_EPOS_Entry]" _
& " ([Trade_Activity_Code]) " _
& " VALUES " _
& " (#Trade_Activity_Code)"
Dim strMessage As String = "Successfully saved"
Dim resultColor As Drawing.Color = Drawing.Color.Green
Using cmd = New SqlCommand(strQuery, con)
cmd.Parameters.AddWithValue("#Trade_Activity_Code", tcodeVar)
Try
con.Open()
cmd.ExecuteNonQuery()
resultSQL.ForeColor = Drawing.Color.Green
resultSQL.Text = "Successfully Saved"
Catch ex As SqlException
strMessage = ex.Message
resultColor = Drawing.Color.Red
Finally
con.Close()
End Try
End Using
// Write results outside of db operation
Response.Write(strMessage)
resultSQL.ForeColor = resultColor
resultSQL.Text = strMessage
Of course the above assumes there's an instanciated, unopen con connection variable present.
Notice that it also only catches SqlException. Catching the basic Exception here seems wrong to me.
SECOND UPDATE:
If the above code isn't working, the issue may be caused by an Sql Trigger.
Somewhere not shown in your code, you are assigning the connection to the command object (this is for the first query).
When you get to the second query, you're redefining the cmd object as a new object, which is also removing any reference to the connection as established earlier.
Try this for your second block of code:
strQuery = "INSERT INTO [SD_EPOS_Entry]" _
& " ([Trade_Activity_Code] " _
& " VALUES " _
& " (#Trade_Activity_Code1)"
cmd = New SqlCommand(strQuery, cnn) 'Define the connection to be used for the command.
Hi I am trying to insert data into Navision database from a DataTable. That DataTable contain around 5000 records, if the records count is less then it's working fine but record count is around 5000 I am getting this error.
ERROR - unable to allocate an environment handle.
This is the code I am using
Public Function InsertToHHTTransferLine(ByVal dtTransferLn As DataTable, ByVal hhtNumber As String) As Integer
Dim result As Integer
Dim cn As OdbcConnection
Dim dtTransferLine As DataTable
cn = New OdbcConnection(ConnStr)
Dim SqlStr As String = ""
Try
cn.Open()
dtTransferLine = dtTransferLn
Dim DocType As String
DocType = "Purchase"
Dim cmd As OdbcCommand
Dim hhtNo As String
hhtNo = hhtNumber
If dtTransferLine.Rows.Count > 0 Then
For i As Integer = 0 To dtTransferLine.Rows.Count - 1
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "0" Then
DocType = "Purchase"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "1" Then
DocType = "Transfer Receipt"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "2" Then
DocType = "Transfer Shipment"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "3" Then
DocType = "Stock Count"
End If
Try
SqlStr = "INSERT INTO ""HHT & Navision Line""(""Document Type"",""Document No_"",""HHT No_"",""Line No_"",""Item No_"",""Document Quantity"",""Scan Quantity"",""Unit Price"",""Posted"") VALUES('" & DocType & "','" & dtTransferLine.Rows(i)("DOC_NO").ToString() & "','" & hhtNo & "','" & dtTransferLine.Rows(i)("LINE_NO").ToString() & "','" & dtTransferLine.Rows(i)("ITEM_NO").ToString() & "'," & dtTransferLine.Rows(i)("DOC_QTY").ToString() & "," & dtTransferLine.Rows(i)("SCAN_QTY").ToString() & "," & dtTransferLine.Rows(i)("UNIT_PRICE").ToString() & ",0)"
cmd = New OdbcCommand(SqlStr, cn)
result = cmd.ExecuteNonQuery()
Catch ex As Exception
If (ex.Message.IndexOf("Illegal duplicate key") <> -1) Then
CreateLog(SqlStr, "User1", "Duplicate()", ex.Message)
Else
CreateLog(SqlStr, "User1", "Other()", ex.Message)
End If
'CreateLog(SqlStr, "User1", "Other()", ex.Message)
End Try
Next
End If
Catch ex As Exception
CreateLog(SqlStr, "User1", "InsertToHHTTransferLine()", ex.Message)
result = -1
Finally
cn.Close()
cn.Dispose()
End Try
Return result
End Function
Could be that "cmd" variables need to be disposed before creating new ones?
At least this is the only thing I can see in the code where you are consuming resources in a loop depending on the number of records.
Anyway this should be easy to identify with a debugger, just figure out the line giving you the error, and that will lead you to the answer.