Update multi table access db using vb.net - vb.net

Can someone please help me with that?
My prob is that When i use dataAdapter.Update in this next construction i get a return value of zero (no line was updated but no reason or errors return).
The update sentense works when i run it using Access and other update requests works fine when i work on a single table.
Im Using:
vb.net \ visual studio 2012 \ access 2010 DB
I update the Data on my DataGridView and call the update function:
update command:
Private Function createGeneralUpdateStatement() As String
Return "UPDATE EntitysDataTbl INNER JOIN ManagersExtraDataTbl ON EntitysDataTbl.entityID = ManagersExtraDataTbl.managerID " + _
"SET EntitysDataTbl.entityUserName = [#EntitysDataTbl].entityUserName, " + _
"EntitysDataTbl.entityLastEntry = [#EntitysDataTbl].entityLastEntry, " + _
"ManagersExtraDataTbl.mPassword = [#ManagersExtraDataTbl].mPassword, " + _
"ManagersExtraDataTbl.workGroup = [#ManagersExtraDataTbl].workGroup, " + _
"ManagersExtraDataTbl.entityAccessType = [#ManagersExtraDataTbl].entityAccessType, " + _
"ManagersExtraDataTbl.mActive = [#ManagersExtraDataTbl].mActive" + _
"WHERE EntitysDataTbl.entityID= [#EntitysDataTbl].entityID"
End Function
The parameters are:
Dim parmList(2) As String
parmList(0) = "mPassword"
parmList(1) = "entityUserName"
and the update function is:
Public Function updateDB(ByVal updateCommand As String, ByVal parmList() As String, Optional ByVal insertCommand As String = "") As Boolean
Dim res As Boolean = False
SyncLock Me
Try
mainDataSet.EndInit()
mUpdateCommand = New OleDb.OleDbCommand(updateCommand, MyBase.getConnector)
For Each Str As String In parmList
If Not Str Is Nothing Then
If (Str.StartsWith("%")) Then
mUpdateCommand.Parameters.Add("#" & Str.Trim("%"), OleDb.OleDbType.Boolean, MAX_COL_LEN, Str.Trim("%"))
Else
mUpdateCommand.Parameters.Add("[#" & Str & "]", OleDb.OleDbType.VarChar, MAX_COL_LEN, Str)
End If
End If
Next
mDataAdapter.UpdateCommand = mUpdateCommand
If (Not insertCommand.Equals("")) Then
mInsertCommand = New OleDb.OleDbCommand(insertCommand, MyBase.getConnector)
For Each Str As String In parmList
If Not Str Is Nothing Then
'If Str.Equals("RuleIDNum") Then
' Continue For
'End If
If (Str.StartsWith("%")) Then
mInsertCommand.Parameters.Add("#" & Str.Trim("%"), OleDb.OleDbType.Boolean, MAX_COL_LEN, Str.Trim("%"))
Else
mInsertCommand.Parameters.Add("[#" & Str & "]", OleDb.OleDbType.VarChar, MAX_COL_LEN, Str)
End If
End If
Next
mDataAdapter.InsertCommand = mInsertCommand
End If
Dim i As Integer = mDataAdapter.Update(mainDataSet)
'ERROR - i = 0 => NO LINE WAS UPDATED!!!!
res = True
Catch ex As Exception
res = False
End Try
mDBWasUpdated = res
End SyncLock
Return res
End Function

Related

How to fix 'Undefined function 'xxx' in expression' (Excel Function in SQL Query)

I am trying to call an Excel function to a SQL query, but I keep getting the same error : "Undefined function xxx in expression".
I'm working with Excel only due to customer choices.
I've checked if references were missing,
My function is in a valid Module wiht Option Explicit, and it is declared as Public.
And i made sure I had a return value.
Thank you for your time
There is my function
Public Function CalculRamasseCarriste(ByVal lng_QTE As Integer, ByVal str_CodeArticle As String, ByVal lng_QTEmax As Integer) As Boolean
Static lng_cumulQTE As Integer
Static str_Text As String
Static bln_Prendre As Boolean
If str_Text = "" Then
str_Text = str_CodeArticle
ElseIf str_Text <> "" Then
If str_Text <> str_CodeArticle Then
str_Text = str_CodeArticle
lng_cumulQTE = 0
End If
End If
lng_cumulQTE = lng_cumulQTE + lng_QTE
If lng_cumulQTE < lng_QTEmax Then
CalculRamasseCarriste = True
bln_Prendre = True
ElseIf lng_cumulQTE >= lng_QTEmax And bln_Prendre = True Then
CalculRamasseCarriste = True
bln_Prendre = False
Else
CalculRamasseCarriste = False
End If
End Function
And there is my query :
Return_Qry_Ramasse = "SELECT T1.[Adresse], T1.[N° Support], T1.[Code_Article], T1.[Libellé_article] " & _
" FROM [V_Stock$] as T1 " & _
" LEFT JOIN [Cmd$] as T2 on T1.[Code_Article] = T2.[Code_Article] " & _
" WHERE CalculRamasseCarriste(T1.[Nb Box-Colis / Pal], T1.[Code_Article], T2.[UVC_cmd])= True " & _
" ORDER BY [Code_Article], [Adresse], [N° Support]"

SQL Server (specific) table not updating

I am having a really strange issue with classic asp insert/update that worked flawlessly for years and was never altered. Out of the blue, the table is no longer updating or taking new records. The code does not throw any errors and the SQL Server log shows no errors either. Other tables in the same database work fine so I can insert and update without issues.
Is there a way to find out what is happening with this table or whether it is locked for some reason. I restarted SQL Server and web application, even the server and no luck.
I updated the table directly in SQL Server and it updates and inserts new records fine.
I used the same code on another table and was able to update records.
Can someone please point me in the right direction as I am out ideas on what may be causing this.
Thanks in advance.
Here is the code:
<%
' *** Edit Operations: (Modified for File Upload) declare variables
Dim MM_editAction
Dim MM_abortEdit
Dim MM_editQuery
Dim MM_editCmd
Dim MM_editConnection
Dim MM_editTable
Dim MM_editRedirectUrl
Dim MM_editColumn
Dim MM_recordId
Dim MM_fieldsStr
Dim MM_columnsStr
Dim MM_fields
Dim MM_columns
Dim MM_typeArray
Dim MM_formVal
Dim MM_delim
Dim MM_altVal
Dim MM_emptyVal
Dim MM_i
MM_editAction = CStr(Request.ServerVariables("SCRIPT_NAME"))
If (UploadQueryString <> "") Then
MM_editAction = MM_editAction & "?" & Server.HTMLEncode(UploadQueryString)
End If
' boolean to abort record edit
MM_abortEdit = false
' query string to execute
MM_editQuery = ""
%>
<%
' *** Insert Record: (Modified for File Upload) set variables
If (CStr(UploadFormRequest("MM_insert")) = "update") Then
MM_editConnection = MM_ar_inventory_STRING
MM_editTable = "Artists"
MM_editRedirectUrl = "artists_add.asp?status=ok"
MM_fieldsStr = "ArtistName|value|WebsiteStatus|value|Biography|value|Notes|value|ImageFileName|value|ModifiedBy|value|DT|value|IpAddress|value"
MM_columnsStr = "ARTST_Artist|',none,''|ARTST_WebsiteStatus|',none,''|ARTST_Biography|',none,''|ARTST_Notes|',none,''|ARTST_ArtistImageFileName|',none,''|ARTST_ModifiedBy|',none,''|ARTST_LastModified|',none,NULL|ARTST_LastModifiedIP|',none,''"
' create the MM_fields and MM_columns arrays
MM_fields = Split(MM_fieldsStr, "|")
MM_columns = Split(MM_columnsStr, "|")
' set the form values
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_fields(MM_i+1) = CStr(UploadFormRequest(MM_fields(MM_i)))
Next
' append the query string to the redirect URL
If (MM_editRedirectUrl <> "" And UploadQueryString <> "") Then
If (InStr(1, MM_editRedirectUrl, "?", vbTextCompare) = 0 And UploadQueryString <> "") Then
MM_editRedirectUrl = MM_editRedirectUrl & "?" & UploadQueryString
Else
MM_editRedirectUrl = MM_editRedirectUrl & "&" & UploadQueryString
End If
End If
End If
%>
<%
' *** Insert Record: (Modified for File Upload) construct a sql insert statement and execute it
Dim MM_tableValues
Dim MM_dbValues
If (CStr(UploadFormRequest("MM_insert")) <> "") Then
' create the sql insert statement
MM_tableValues = ""
MM_dbValues = ""
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_formVal = MM_fields(MM_i+1)
MM_typeArray = Split(MM_columns(MM_i+1),",")
MM_delim = MM_typeArray(0)
If (MM_delim = "none") Then MM_delim = ""
MM_altVal = MM_typeArray(1)
If (MM_altVal = "none") Then MM_altVal = ""
MM_emptyVal = MM_typeArray(2)
If (MM_emptyVal = "none") Then MM_emptyVal = ""
If (MM_formVal = "") Then
MM_formVal = MM_emptyVal
Else
If (MM_altVal <> "") Then
MM_formVal = MM_altVal
ElseIf (MM_delim = "'") Then ' escape quotes
MM_formVal = "'" & Replace(MM_formVal,"'","''") & "'"
Else
MM_formVal = MM_delim + MM_formVal + MM_delim
End If
End If
If (MM_i <> LBound(MM_fields)) Then
MM_tableValues = MM_tableValues & ","
MM_dbValues = MM_dbValues & ","
End If
MM_tableValues = MM_tableValues & MM_columns(MM_i)
MM_dbValues = MM_dbValues & MM_formVal
Next
MM_editQuery = "insert into " & MM_editTable & " (" & MM_tableValues & ") values (" & MM_dbValues & ")"
If (Not MM_abortEdit) Then
' execute the insert
Set MM_editCmd = Server.CreateObject("ADODB.Command")
MM_editCmd.ActiveConnection = MM_editConnection
MM_editCmd.CommandText = MM_editQuery
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
If (MM_editRedirectUrl <> "") Then
Response.Redirect(MM_editRedirectUrl)
End If
End If
End If
%>
I notice that UploadQueryString is undefined so if you add this as the fist line
<%OPTION EXPLICIT%>
I guess that you will get some meaningful error messages
The craziest solution to the problem that totally seems unrelated was to disable Symantec Endpoint Protection (Network Protection) and it worked for a reason I cannot possibly explain! Thank you all for the suggestions above.

Unable write to SQL from VBA/Excel using ADO

I'm using VBA for working with SQL database, Select commands forking fine, problem is with modification of dbase - insert, delete. If I using external application for work with DBase, everything is OK, thats mean - my privilegs is OK. On example Select is done successfully, rest not...
Thanks for your help.
JB
Public LinkID As ADODB.Connection
Public QueryID As ADODB.Recordset
Private Record() As String
Public Row As Long
Public NumRows As Long
Public Function connect(Optional server As String = "", Optional uid As String = "", Optional pwd As String = "", _
Optional dbname As String = "") As Boolean
Dim connStr As String
If (server = "") Then server = "DBServer"
If (uid = "") Then uid = "User1"
If (pwd = "") Then pwd = "1234"
If (dbname = "") Then dbname = "Database1"
If (uid = "") Then
connStr = "DRIVER={SQL Server};SERVER=" & server & ";Trusted_Connection=Yes;APP=Office 2007 App;DATABASE=" & dbname
Else
'connStr = "DRIVER={SQL Server};SERVER=" & server & ";UID=" & uid & ";PWD=" & pwd & ";APP=Office 2007 App;DATABASE=" & dbname
connStr = "Provider=SqlOleDb;Data Source=DBServer;Initial Catalog = Database1;UID=" & uid & ";PWD=" & pwd & ";Options=-1;"
End If
If (LinkID Is Nothing) Then
Set LinkID = New ADODB.Connection
On Error Resume Next
LinkID.Open connStr
On Error GoTo 0
If (LinkID.State = 0) Then
ErrorNo = Err.Number
ErrorTxt = Err.Description
End If
End If
connect = LinkID.State
End Function
Public Function query(Optional queryStr As String = "") As Boolean
If (queryStr = "") Then Exit Function
If Not (connect) Then Exit Function
If (QueryID Is Nothing) Then
Set QueryID = New ADODB.Recordset
ElseIf (QueryID.State) Then
free_result
End If
On Error Resume Next
QueryID.Open queryStr, LinkID, adOpenForwardOnly, adLockOptimistic, -1 ', adLockBatchOptimistic
On Error GoTo 0
Row = 0
If (QueryID.State = 0) Then
ErrorNo = Err.Number
ErrorTxt = Err.Description
End If
NumRows = count_records
query = QueryID.State
End Function
Public Sub free_result()
If Not (QueryID Is Nothing) Then
QueryID.Close
End If
End Sub
Public Function count_records() As Integer
count_records = 0
If Not (QueryID Is Nothing) Then
If (QueryID.State) Then
While (Not QueryID.EOF)
count_records = count_records + 1
QueryID.MoveNext
Wend
If (count_records) Then
QueryID.Requery
End If
End If
End If
End Function
Sub Test()
query "SELECT * FROM Table1 WHERE Empl = 'Tom'"
query "INSERT INTO Table1 (EMPL)Values ('Tod')"
query "DELETE FROM Table1 WHERE Empl = 'Tod'"
End Sub
RecordSet.Open is only used to open a cursor (select) not execute some DML. For this you can use Connection.Execute. The last can also be used to create a RecordSet.
See for example [http://msdn.microsoft.com/en-us/library/ms807027.aspx]

Error: Index and length must refer to a location within the string

Im getting the following exception on vb.net. I have trouble solving this error:
Error 5: Index and length must refer to a location within the string.Parameter name: length.
here is my code :
Private Sub attemptedNumbersNew2(ByVal date_start As DateTime, ByVal date_end As DateTime, ByVal port As String, ByVal team As String)
Dim con As New ADODB.Connection
Dim recordS As New ADODB.Recordset
Dim sql As String = "some query...."
Try
con.Open(connectStringA)
recordS.Open(sql, con)
If recordS.EOF Then
Else
Do While Not recordS.EOF
Dim temp As String
If name4number.Contains(lastAttempted) Then
temp = name4number.Item(lastAttempted)
Else
temp = lastAttempted
End If
If attemptedNames.Equals("NONE") Or attemptedNames.Equals("") Then
attemptedNames = temp
ElseIf Not temp.Equals("") Then
attemptedNames = attemptedNames & " - " & temp
End If
If agentsHashOffered.Contains(temp & "_" & team) Then
agentsHashOffered.Item(temp & "_" & team) = agentsHashOffered.Item(temp & "_" & team) + 1
Else
agentsHashOffered.Add(temp & "_" & team, 1)
End If
If recordS.Fields(2).Value >= oldDate Then
If answeringNumber.Equals("NONE") Then
answeringNumber = recordS.Fields(4).Value
If answeringNumber.Substring(0, 1).Equals("9") Then
answeringNumber = answeringNumber.Substring(1, 10)
End If
callDuration = -1
End If
disconnectionTime = recordS.Fields(3).Value
Else
End If
If attempted.Equals("NONE") Then
attempted = recordS.Fields(4).Value
If attempted.Substring(0, 1).Equals("9") Then
attempted = attempted.Substring(1, 10)
End If
attemptedCount = attemptedCount + 1
lastAttempted = attempted
Else
temp = recordS.Fields(4).Value
If temp.Substring(0, 1).Equals("9") Then
temp = temp.Substring(1, 10)
End If
attempted = attempted & " - " & temp
attemptedCount = attemptedCount + 1
lastAttempted = temp
End If
recordS.MoveNext()
Loop
End If
con.Close()
con = Nothing
recordS = Nothing
Catch ex As Exception
MsgBox("Error #" & Err.Number & ": " & Err.Description)
End Try
End Sub
It was working fine the other day, but suddenly I started getting this error.
any helps are welcome
THANK YOU in Advance

Recursive Function Not Returning

I am hopeing someone can help me here with a recursive function I have that is not returning either true or false as I would have espected it to. The function loops through a Active Directory group for its members and then calls itself if it encounters any groups within the membership in order to gets its members as well. I am trying to return either true or false based on if any errors were encountered but not haveing any luck at all. It appears to just hang and never return back to the primary calling sub that starts the recursive function. Below is my code I am using:
Private Sub StartAnalysis(ByVal grp As String, ByVal grpdn As String, ByVal reqid As String)
Dim searchedGroups As New Hashtable
'prior work before calling sub
searchedGroups.Add(grp, 1)
Dim iserror As Boolean = GetGroupMembers(grpdn, searchedGroups, reqid)
If iserror = False Then
'do stuff
Else
'do stuff
End If
'cleanup
End Sub
Public Function GetGroupMembers(ByVal groupSearch As String, ByVal searchedGroups As Hashtable, ByVal requestID As String) As Boolean
Dim iserror As Boolean = False
Try
Dim lastQuery As Boolean = False
Dim endLoop As Boolean = False
Dim rangeStep As Integer = 999
Dim rangeLow As Integer = 0
Dim rangeHigh As Integer = rangeLow + rangeStep
Do
Dim range As String = "member"
If lastQuery = False Then
range = String.Format("member;range={0}-{1}", rangeLow, rangeHigh)
Else
range = String.Format("member;range={0}-*", rangeLow)
endLoop = True
End If
Dim group As SearchResult = QueryObject(groupSearch, range)
Dim groupCN As String = group.Properties("cn")(0).ToString
If group.Properties.Contains(range) Then
For Each member As Object In group.Properties(range)
Dim user As SearchResult = QueryObject(member.ToString, "member")
Dim userCN = user.Properties("cn")(0).ToString
If Not user.Properties.Contains("member") Then
Dim userMail = String.Empty
If user.Properties.Contains("mail") Then
userMail = user.Properties("mail")(0).ToString
End If
userCN = userCN.Replace("'", "''")
Dim qry As String = _
"INSERT INTO group_analysis_details (request_id, member_name, member_email, member_group) " & _
"values ('" & requestID & "', '" & userCN & "', '" & userMail & "', '" & groupCN & "')"
Dim sqlConn As SqlConnection = New SqlConnection(cs)
Dim sqlCmd As SqlCommand = New SqlCommand(qry, sqlConn)
sqlConn.Open()
sqlCmd.ExecuteNonQuery()
sqlConn.Close()
sqlCmd.Dispose()
sqlConn.Dispose()
Else
If Not searchedGroups.ContainsKey(userCN) Then
searchedGroups.Add(userCN, 1)
iserror = GetGroupMembers(user.Properties("distinguishedname")(0).ToString, searchedGroups, requestID)
If iserror = True Then Return iserror
Else
searchedGroups(userCN) += 1
End If
End If
Next
Else
lastQuery = True
End If
If lastQuery = False Then
rangeLow = rangeHigh + 1
rangeHigh = rangeLow + rangeStep
End If
Loop While endLoop = False
Return iserror
Catch ex As Exception
myEvents.WriteEntry("Error while analyzing the following group: " & groupSearch & vbCrLf & vbCrLf & _
"Details of the error are as follows: " & ex.Message, EventLogEntryType.Error)
Return True
End Try
End Function
Hopefully someone can point out where I might be making my error is this.
Thanks,
Ron
Generally if you're using a 'Do...Loop While' and manually setting the exit condition inside the loop it's very easy to get stuck in an infinite loop which is what causes the program to hang.
It looks like you're not setting endloop = True in all circumstances. Try changing it to an Exit Do and adding one to each of the various conditions you have. A bit of trial and error will be required to get it just right.
Also to make your life easier extract the database insert code into a seperate function and call it when needed.