SQL Program UPDATE Record Error - vb.net

I'm working in a small SQL Database program. The programs just there to view, edit and update the database records. Everything is working remarkably well considering I've never tried something like this before. I've managed to get the Add Records, Refresh Records and Delete Records functions working flawlessly. However, I've hit a little bump when trying to UPDATE a selected record.
To clarify, the SQL Table is displayed in a list view, from this list view the end-user can select a particular-record and either edit or delete it.
The edit button opens a new form window with text fields which are automatically filled with the current information of that record.
The code for the edit record form is:
Private Sub frmEdit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
intDB_ID_Selected = CInt(frmMain.lvRec.SelectedItems(0).Text)
Call dispCaption()
Call dispInfo() 'Display the info of the selected ID
End Sub
Private Sub dispInfo()
SQL = "Select * from PersonsA " & _
"where Members_ID=" & intDB_ID_Selected & ""
With comDB
.CommandText = SQL
rdDB = .ExecuteReader
End With
If rdDB.HasRows = True Then
rdDB.Read()
Me.midtxt.Text = rdDB!Members_ID.ToString.Trim
Me.gttxt.Text = rdDB!Gamer_Tag.ToString.Trim
Me.sntxt.Text = rdDB!Screenname.ToString.Trim
Me.fntxt.Text = rdDB!First_Name.ToString.Trim
Me.lntxt.Text = rdDB!Last_Name.ToString.Trim
Me.dobtxt.Text = rdDB!DoB.ToString.Trim
Me.dobtxt.Text = rdDB!DoB.ToString.Trim
Me.emailtxt.Text = rdDB!E_Mail_Address.ToString.Trim
Me.teamptxt.Text = rdDB!Position.ToString.Trim
Me.ugctxt.Text = rdDB!Cautions.ToString.Trim
Me.recordtxt.Text = rdDB!Record.ToString.Trim
Me.eventatxt.Text = rdDB!Event_Attendance.ToString.Trim
Me.Mstattxt.Text = rdDB!Member_Status.ToString.Trim
End If
rdDB.Close()
End Sub
Private Sub dispCaption()
End Sub
Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
Call disControl()
'Validation
If invalidUpdateEntry() = True Then
Call enaControl()
Exit Sub
End If
'Prompt the user if the record will be updated
If MsgBox("Are you sure you want to update the selected record?", CType(MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2 + MsgBoxStyle.Question, MsgBoxStyle), "Update") = MsgBoxResult.Yes Then
'Update query
SQL = "Update PersonsA" & _
"SET Members_ID='" & Me.midtxt.Text.Trim & "'," & _
"Gamer_Tag='" & Me.gttxt.Text.Trim & "'," & _
"Screenname='" & Me.sntxt.Text.Trim & "'," & _
"First_Name='" & Me.fntxt.Text.Trim & "'," & _
"Last_Name='" & Me.lntxt.Text.Trim & "'," & _
"DoB='" & Me.dobtxt.Text.Trim & "'," & _
"E_Mail_Address='" & Me.emailtxt.Text.Trim & "'," & _
"Position='" & Me.teamptxt.Text.Trim & "'," & _
"U_G_Studio='" & Me.ugptxt.Text.Trim & "'," & _
"Cautions='" & Me.ugctxt.Text.Trim & "'," & _
"Record='" & Me.recordtxt.Text.Trim & "'," & _
"Event_Attendance='" & Me.eventatxt.Text.Trim & "'," & _
"Member_Status='" & Me.Mstattxt.Text.Trim & "'" & _
"WHERE Members_ID='" & intDB_ID_Selected & "'"
Call execComDB(SQL) 'Execute the query
Me.Close()
'*** Refresh the list
SQL = "Select * from PersonsA "
Call frmMain.dispRec(SQL)
'--- End of refreshing the list
Exit Sub
Else
Call enaControl()
End If
End Sub
As I've said, I've been able to do everything else using an extremely similar method, but when I try to UPDATE the record I get an error saying
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'Members_ID'.
I know it's this line that's the problem
"WHERE Members_ID='" & intDB_ID_Selected & "'"
Call execComDB(SQL) 'Execute the query
But referencing 'intDB_ID_Selected' has always worked before, and it's been set-up on the update form records load as intDB_ID_Selected = CInt(frmMain.lvRec.SelectedItems(0).Text)
I know this is a huge thread but if anyone could steer me in the right direction WITHOUT telling me to re-write the entire statement I'd be forever grateful.
EDIT1: I fixed the comma before the WHERE clause, but I'm still getting the same error.

Missing a space between
"Update PersonsA " & _
"SET Members_ID= ....
and (as already pointed out) a comma not needed before the WHERE
Said that, do a favor to yourself and to your users. Do not use string concatenation to build a sql command. Use always a parameterized query.
Just as an example
SQL = "Update PersonsA SET Members_ID=#id, Gamer_Tag=#tag, Screenname=#screen," & _
"First_Name=#fname,Last_Name=#lname,DoB=#dob,E_Mail_Address=#email," & _
"Position=#pos,U_G_Studio=#studio,Cautions=#caution,Record=#rec," & _
"Event_Attendance=#event, Member_Status=#stat " & _
"WHERE Members_ID=#id"
SqlCommand cmd = new SqlCommand(SQL, connection)
cmd.Parameters.AddWithValue("#id", Me.midtxt.Text.Trim)
..... so on for the other parameters defined above ....
cmd.ExecuteNonQuery();

Change "Member_Status='" & Me.Mstattxt.Text.Trim & "'," & _
to "Member_Status='" & Me.Mstattxt.Text.Trim & "'" & _
Looks like it was just an extra rogue comma!

On any error like this, use debugging provided with Visual Studio. Inspect the value of SQL, paste into MS SQL Management Studio - it has syntax highlight, and you should be able to spot the error easily.
To prevent further issues (including SQL injection vulnerability), separate this query into an embedded resource, and use parameters. Then it's easy to view, maintain (you can copy/paste between SQL Mgmt Studio and VS), and ultimately use it in code.
A side note, you don't need to use Call in VB.NET, just put a method name with parenthesis.

Related

INSERT INTO - errors, but allows input into table

For reasons I cannot see I get the following error message:
Compile error: Method or data member not found
when I use the following:
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Once I click OK and use the refresh button the entry is put into the database, but each time I do an entry I have to go to the same process.
I would like to figure out what method or data is missing?
I should add that there is an outnumber primary key field on this table (Berth_ID), and each time I use the cmd_Add button a new ID number is created for the new record. This includes creating a new ID number for the new record that triggers the error.
Here is all the VBA associated with this form
Private Sub Form_Load()
DoCmd.RunCommand acCmdRecordsGoToLast
End Sub
Private Sub LOCATION_Change()
Me.txt_Cur_Flo = Me.LOCATION.Column(1)
Me.txt_Cur_Doc = Me.LOCATION.Column(2)
Me.txt_Cur_Ori = Me.LOCATION.Column(3)
End Sub
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Private Sub cmd_Clear_Click()
Me.Add_Boat = ""
Me.LOCATION = ""
Me.txt_Cur_Flo = ""
Me.txt_Cur_Doc = ""
Me.txt_Cur_Ori = ""
Me.Add_Boat.SetFocus
End Sub
Private Sub cmd_Close_Click()
DoCmd.Close
End Sub
Consider the best practice of parameterization and not string concatenation of SQL mixed with VBA variables. Due to missing quotes, the compiler attempts to reference a column name and not its literal value. Instead, consider parameterization with defined types which is supported with Access SQL using QueryDefs. Notice below, SQL and VBA are complete separate.
SQL (save as stored query)
PARAMETERS prmBoat TEXT, prmLoc INT, prmBerthed INT;
INSERT INTO BERTHAGE (BOAT, LOCATION, BERTHED)
VALUES(prmBoat, prmLoc, prmBerthed)
VBA
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdef = db.QueryDefs("mySavedParamQuery")
' BIND PARAM VALUES
qdef!prmBoat = Me.Add_Boat
qdef!prmLoc = Me.LOCATION
qdef!prmBerthed = Me.In_Port
' EXECUTE ACTION QUERY
qdef.Execute
Set qdef = Nothing
Set db = Nothing
Even better, save your query with form controls intact and simply call OpenQuery:
SQL (save as stored query)
INSERT INTO BERTHAGE(BOAT, LOCATION, BERTHED)
VALUES(Forms!myForm!Add_Boat, Forms!myForm!LOCATION, Forms!myForm!In_Port)
VBA
Private Sub cmd_Add_Click()
Dim strSQL As String
DoCmd.SetWarnings False ' TURN OFF APPEND PROMPTS
DoCmd.OpenQuery "mySavedActionQuery"
DoCmd.SetWarnings True ' RESET WARNINGS
Call cmd_Clear_Click
End Sub
Missing opening parenthesis after VALUES. Also missing apostrophe in front of Me.Add_Boat. These special characters must always be in pairs, an even number by counting.
If Berth_Week and Berth_Year are number fields (and should be), don't use apostrophe delimiters.
If In_Port is a Yes/No field, don't use apostrophe delimiters.
The issue appears to be that I was doubling up the inputs into the 'week' and 'year' field. this was happening (I believe) because those text box fields were already accessing the week and year information directly from the default value on the BERTHAGE table. Essentially I went through each input and would run it individually waiting for the error to occur. Once it occurred I took it out of the INSERT INFO statement. With the removal of week and year, everything is working. That was a painful exercise, and still not complete, but I am back to a function form/DB so I'll take the small victories when they occur.
Private Sub cmd_Add_Click()
Dim strSQL As String
CurrentDb.Execute " INSERT INTO BERTHAGE " & "(BOAT, LOCATION, BERTHED) VALUES ('" & Me.Add_Boat & "'," _
& Me.New_Loc & "," _
& Me.In_Port & ");"
cmd_Clear_Click
DoCmd.Requery
End Sub`

Update Access database using Visual Studio 2015 - VB.net

I am trying to do a simple update to an Access 2016 database. I am using Visual Studio/VB.net. I have been able to do this already on a different form with no issues using the same type of coding (it's pretty basic, it was for a school project but not anymore). I have tried two different ways to do this...using the update table adapter, for example:
MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
AvailabilityTextBox.Text, EmailTextBox.Text)
Using that method I always get a notImplemented exception thrown even though I have used a similar type of adapter elsewhere. Also I tried using a strung method (I know, not ideal):
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
But this method gives me the error of Syntax Error in UPDATE statement. Again I have used this method elsewhere with no problems. Below I will post all the code for this form.
Imports System.Data
Imports System.Data.Odbc ' Import ODBC class
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class editMediators
Dim NewData As Boolean
Dim objConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ECRDatabase.accdb")
' create functions for save or update
Private Sub runAccessSQL(ByVal sql As String)
Dim cmd As New OleDbCommand
connect() ' open our connection
Try
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Close()
MsgBox("Data Has Been Saved !", vbInformation)
Catch ex As Exception
MsgBox("Error when saving data: " & ex.Message)
End Try
End Sub
Private Sub editMediators_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.MediatorsListTableAdapter.Fill(Me.ECRDatabaseDataSet.mediatorsList) 'loads current mediator information
DateTimePicker1.Value = Today()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'update button
NewData = True
alertMsgBox2()
End Sub
Private Sub alertMsgBox2()
Select Case MsgBox("Yes: Saves Changes," & vbNewLine &
"No: Exits the mediator update window without saving," & vbNewLine &
"Cancel: Returns to the mediator update window.", MsgBoxStyle.YesNoCancel, "Update Mediator Information")
Case MsgBoxResult.Yes
MediatorsListBindingSource.EndEdit()
updateMediator()
'intentionally commented out
'MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
'AvailabilityTextBox.Text, EmailTextBox.Text)
' Me.Close()
Case MsgBoxResult.No
MediatorsListBindingSource.CancelEdit()
Me.Close()
End Select
End Sub
Private Sub updateMediator()
Dim saveInfo As String
If NewData Then
Dim Message = MsgBox("Are you sure you want to update mediator information? ", vbYesNo + vbInformation, "Information")
If Message = vbNo Then
Exit Sub
End If
Try
'Update mediator information
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
Catch ex As Exception
End Try
Else
Exit Sub
End If
runAccessSQL(saveInfo)
End Sub
There is obviously something I am missing, though I am not sure it is missing from the code. I checked my database fields and set them to string/text fields just to see if I could get it working. At one time, I had two 2 phone number fields that were set to to the wrong data type so you could only enter a number per int32 requirements. I actually had one of these methods working/updating the db several months ago but I can't figure out what happened since. I do know Visual Studio gave me some problems which probably contributed but it's been too long to remember what happened.
I am rather lost on what else to try as this seems like it should work one way or another. Any ideas what to look at and/or try?? Hopefully I can be pointed in the right direction.
Thanks :)
Your update statement is incorrect, the WHERE clause is inside the VALUES() segment, and should be after it.
Try this instead:
(Edited)
saveInfo = "UPDATE mediatorsList SET mediatorName='" & _
MediatorNameTextBox.Text & "', email='" & EmailTextBox.Text & "', .... WHERE " & _
mediatorID = '" & MediatorIDTextBox.Text & "'"
Also be sure to handle the date correctly. I usually force formatting in yyyy/mmm/dd format.

MS ACCESS - Error runtime 3141 SQL in VBA

I'm getting error in ms access while trying change subform recordsource based on combo box
The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect.
here my code
Private Sub Text4_AfterUpdate()
If (Me.Text4.Value = "(ALL)") Then
filterORIGIN_COD = "SELECT SUMMARY.DEST_CITY, SUMMARY.DESTINATION, Count(SUMMARY.CNOTE_NO) AS CountOfCNOTE_NO1" & _
"FROM SUMMARY" & _
"WHERE (((SUMMARY.ORIGIN_CODE) Like " & "'" * "'" & ")))" & _
"GROUP BY SUMMARY.DEST_CITY, SUMMARY.DESTINATION, SUMMARY.TGL_DATA, SUMMARY.ORIGIN_CODE, SUMMARY.ORIGIN, SUMMARY.DEST_CODE;"
Else
filterORIGIN_COD = "SELECT SUMMARY.DEST_CITY, SUMMARY.DESTINATION, Count(SUMMARY.CNOTE_NO) AS CountOfCNOTE_NO1" & _
"FROM SUMMARY" & _
"WHERE (((SUMMARY.ORIGIN_CODE)=" & """Me![Text4]""" & ")))" & _
"GROUP BY SUMMARY.DEST_CITY, SUMMARY.DESTINATION, SUMMARY.TGL_DATA, SUMMARY.ORIGIN_CODE, SUMMARY.ORIGIN, SUMMARY.DEST_CODE;"
End If
Me![OUTBOUND_DETAIL].Form.RecordSource = filterORIGIN_COD
Me![OUTBOUND_DETAIL].Requery
End Sub
ADDITIONAL
actually I'm trying to filter subform (query record source), can someone show me better ways to do that? :)
If trying to filter subform in a trigger event, simply use DoCmd.ApplyFilter or DoCmd.SetFilter (for Access 2010+) methods which are also available in macros:
Private Sub Text4_AfterUpdate()
DoCmd.ApplyFilter , "[SUMMARY.ORIGIN_CODE]='" & Me![Text4] & "'"
End Sub

VB.NET use variable in textbox name

OK, so I have a form called quote_guidelines and i would like to use a procedure to update my database with values entered into the quote_guidelines form. The values are the descriptions and costs of decorations, food/drink and entertainment. Each tab has been assigned one of these additional servies. I wanted to make a procedure which would update the database with these new values.
The problem was that the query would have to contain a different table and different textbox names. I tried to solve this by saving the names of the tables and textboxes in variables, which will then be passed into the procedure.
the table variable works fine in the sql statement however, the textbox names dont.
I tried this:
quote_guidelines.Controls(description_textbox).Text
But this doesnt work.
Here is my query:
query = "UPDATE " & additional & " SET description='" & quote_guidelines.Controls("" & description_textbox & "").Text & "', cost= " & quote_guidelines.Controls("" & cost_textbox & "").Text & " WHERE " & additional & "ID='" & y & "'"
When I run the program, i get the following error "An unhandled exception of type 'System.NullReferenceException' occurred in EHCC_BookingSystem.exe
Additional information: Object reference not set to an instance of an object."
I just realised that it might be some other stupid mistake i've made so here's the whole procedure:
Sub UpdateAdditionals(textbox3 As System.Object, textbox4 As System.Object, textbox5 As System.Object, textbox6 As System.Object, textbox7 As System.Object, textbox8 As System.Object, ByRef additional As String, ByRef description_textbox As String, ByRef cost_textbox As String)
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "Server=localhost;userid=root;password=root;database=comp4"
Dim reader As MySqlDataReader
MsgBox(additional & description_textbox & cost_textbox)
Try
mysqlconn.Open()
Dim query As String
query = "UPDATE " & additional & " SET description='" & quote_guidelines.Controls.Find(description_textbox, True).FirstOfDefault().Text & "', cost= " & quote_guidelines.Controls.Find(cost_textbox, True).FirstOfDefault().Text & " WHERE " & additional & "ID='" & y & "'"
MsgBox(query)
command = New MySqlCommand(query, mysqlconn)
reader = command.ExecuteReader()
mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub
Try this - Replaced Controls in Controls.Find (Note the `True parameter to search the controls children):
query = "UPDATE " & additional & " SET description='" & TryCast(quote_guidelines.Controls.Find(description_textbox, True)(0), TextBox).Text & "', cost= " & TryCast(quote_guidelines.Controls.Find(cost_textbox, True)(0).Text & " WHERE " & additional & "ID='" & y & "'"
Also note you could do .FirstOfDefault() to get the first control (don't forget to cast):
Controls.Find("nameofcontrol", True).FirstOfDefault()

Insert SQL Query not executed

I am doing the programming on my computer and it works fine-the program, the database itself, inserting to the database is also working fine. But when I publish it and install the program on another computer. It crashes and does not execute the INSERT command.
Here is my code.
Private Sub cmdBlank_Click(sender As System.Object, e As System.EventArgs) Handles cmdBlank.Click
strTariff1 = txtPart1.Text & " " & txtPName1.Text & " " & txtQty1.Text & " " & txtU1.Text
strTariff2 = txtPart2.Text & " " & txtPName2.Text & " " & txtQty2.Text & " " & txtU2.Text
strTariff3 = txtPart3.Text & " " & txtPName3.Text & " " & txtQty3.Text & " " & txtU3.Text
strTariff4 = txtPart4.Text & " " & txtPName4.Text & " " & txtQty4.Text & " " & txtU4.Text
'strTariff5 = txtPart5.Text & " " & txtPName5.Text & " " & txtQty5.Text & " " & txtU5.Text
Call saveToDb()
frmreportax.Show()
End Sub
Private Function saveToDb()
conn.Close()
Dim cmdAdd, cmdCount, cmdAdd2 As New iDB2Command
Dim sqlAdd, sqlCount, sqlAdd2 As String
Dim curr1, curr2, curr3, curr4 As String
Dim count As Integer
conn.ConnectionString = str
conn.Open()
'Check for duplicate entry
sqlCount = "SELECT COUNT(*) AS count FROM cewe WHERE transport=#transport AND blnum=#blnum"
With cmdCount
.CommandText = sqlCount
.Connection = conn
.Parameters.AddWithValue("#transport", frmPart1.txtTransport.Text)
.Parameters.AddWithValue("#blnum", frmPart1.txtNo.Text)
End With
count = Convert.ToInt32(cmdCount.ExecuteScalar())
If count <> 0 Then
MsgBox("Duplicate Entry: " & frmPart1.txtTransport.Text, vbOKOnly + vbExclamation)
Else
sqlAdd = "INSERT INTO cewe (page) " & _
"VALUES (#page) "
With cmdAdd
.Parameters.AddWithValue("#page", Val(frmPart1.txtPage.Text))
.CommandText = sqlAdd
.Connection = conn
.ExecuteNonQuery()
End With
end if
cmdAdd.Dispose()
cmdAdd2.Dispose()
conn.Close()
end function
Please tell me what I am doing wrong? When I run and install the program on my PC, it works perfectly fine. But when I run/install it on another PC, it crashes after the cmdBlank is clicked.
There could be a number of things causing the issue but the first place to look is any error logs or crash report that may give some indication of the problem. Try debugging or logging to get a better picture. Beyond that there are some small suggestions that may help below.
Does the other computer have access to the database you are pointing to? Is the database connection pointing to localhost? In which case you will want to ensure that you have the same credentials (host, username, password, port etc.) set up on the database server on new computer. Are database drivers installed on new computer? What are the fundamental differences between the two machines?
AS400 iSeries DB2 needs to be updated to version 6.xx.0800 and did the tweak!
Installer can be found here
http://www-03.ibm.com/systems/power/software/i/access/windows_sp.html
Problem solved!