Syntax Error in Update Query (VB.Net) - sql

Please help me. My project uses an access database. This is my code:
Try
Dim SqlQuery As String = "UPDATE Penawaran SET UP = '" & box_up.Text & "', Dari = '" & box_dari.Text & "', Hal = '" & box_hal.Text & "', No_Reference = '" & box_no_reference.Text & "', Email = '" & box_email.Text & "', CC = '" & box_cc.Text & "', No = '" & box_no.Text & "', Bahan_Proses = '" & box_bahan_proses.Text & "', Jumlah = '" & box_jumlah.Text & "', Harga_Satuan = '" & box_harga_satuan.Text & "', Total = '" & box_total.Text & "', Sub_Total = '" & box_sub_total.Text & "', Total_PPN = '" & box_ppn_10_persen.Text & "', Total_Semua = '" & box_total_semua.Text & "', Terbilang = '" & box_terbilang.Text & "', Note = '" & box_note.Text & "', Nama = '" & box_nama.Text & "', Bagian = '" & box_bagian.Text & "' WHERE Kepada = '" & box_kepada.Text & "'"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = Database
.ExecuteNonQuery()
End With
MsgBox("Data yang anda pilih sudah berhasil di ubah & simpan ke dalam sistem.")
Call Sett_pnwrn()
'Me.button_delete.Enabled = False
' Me.button_edit.Enabled = False
Catch ex As Exception
MsgBox(ex.Message)
End Try
Why it doesn't work?
This is the error message :
Syntax error in update statement.
What should I do?

Related

keep getting a "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement" error

Good day, I keep getting a "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement" error.
Can someone please assist with why and where?
Any help will be greatly appriciated
Below is the code
Try
conec.Open()
Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName = '" & TxtName.Text & "', LastName = '" & txtSurname.Text & "', Access = '" & cmbAccess.SelectedItem & "', CreatedBY = '" & Label9.Text & "', DateCreated = '" & Label10.Text & "', ChangedBY = '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd hh:mm tt") & "' WHERE UserName = " & txtUserName.Text & ";")
cmd.CommandType = CommandType.Text
cmd.Connection = conec
cmd.ExecuteNonQuery()
MessageBox.Show("Data Updated" & vbCrLf & "Done")
conec.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Looks like you're missing apostrophes in your where clause, try:
Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName = '" & TxtName.Text & "', LastName = '" & txtSurname.Text & "', Access = '" & cmbAccess.SelectedItem & "', CreatedBY = '" & Label9.Text & "', DateCreated = '" & Label10.Text & "', ChangedBY = '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd hh:mm tt") & "' WHERE UserName = '" & txtUserName.Text & "';")
I recommend using SQL Parameters however, they're a lot easier to maintain.

datatype mismatch in criteria expression vb2010 edit button

I'm getting the error
datatype mismatch in criteria expression vb.net edit button
when I click the edit button on my vb2010 project. Adding and search button works fine but not on edit button.
Here is my code:
Private Sub BtnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnEdit.Click
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\pcInventory.accdb"
myConnection = New OleDbConnection
OpenStr = "Has Open Office"
If TbPCnum.Text = "" Then
MsgBox("Please select data.")
Else
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "update [pctable] set [Person Incharge] = '" & TbPI.Text & "', [DeptSection] = '" & TbDS.Text & "', [Workgroup] = '" & TbWG.Text & "', [Network ID] = '" & TbNI.Text & "', [OS] = '" & TbOS.Text & "', [Processor] = '" & TbProcessor.Text & "', [MOBO] = '" & TbMB.Text & "', [Memory] = '" & TbRAM.Text & "', [HDD] = '" & TbHDD.Text & "', [Product Key] = '" & TbKey.Text & "', [MS Office] = '" & CbMS.SelectedValue & "', [Open Office] = '" & tbOO.Text & "', [Anti Virus] = '" & TbAV.Text & "', [Monitor] = '" & TbMonitor.Text & "', [Email Address] = '" & TbEadd.Text & "', [Date Purchased] = '" & TbDP.Text & "', [Machine Type] = '" & comboMT.SelectedValue & "', [Remarks] = '" & TbRM.Text & "', [Password] = '" & TbPW.Text & "' Where [PCNumber] = '" & TbPCnum.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TbPCnum.Clear()
TbPI.Clear()
TbDS.Clear()
TbWG.Clear()
TbNI.Clear()
TbOS.Clear()
TbProcessor.Clear()
TbMB.Clear()
TbRAM.Clear()
TbHDD.Clear()
TbKey.Clear()
tbOO.Clear()
TbAV.Clear()
TbMonitor.Clear()
TbEadd.Clear()
TbDP.Clear()
TbRM.Clear()
TbPW.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
I suspect that it may be your query string. You sending a string/text instead of an int/number for example.
check through it and make sure that the database column type matches the data you sending through with the query.
Remove the single quotation marks if you sending int/numeric values.

VB.Net Query Syntax Error in MS Access

Dim cmd As OleDb.OleDbCommand = New OleDbCommand(" UPDATE Items SET PartNo = " & PartNoTxt.Text & ", EqptDesc = '" & DescTxt.Text & "', Qty = '" & QtyTxt.Text & "', Pasok = '" & InTxt.Text & "', Labas = '" & OutTxt.Text & "', Tapos = '" & EndTxt.Text & "', SerialNumber = '" & SerialTxt.Text & "', CalibrationType = '" & CalType.Text & "', CalibrationDate = '" & CalOn.Value.Date & "', SupplierDue = '" & SuppDue.Value.Date & "', TodaysDate = '" & TodDate.Value.Date & "', Validity = '" & Validity.Text & "', Status = '" & StatsTxt.Text & "', DiOh = '" & DOTxt.Text & "', User = '" & UserTxt.Text & "', EMType = '" & EMType.Text & "' WHERE CTID = " & TxtItemCode.Text, connection)
I am using MS Access.
Here is the code which I am having problem with, it says "Syntax error in UPDATE statement.".
User is a reserved word in Jet/ACE, so you must surround it with square brackets in your statement:
... & "', [User] = '" & UserTxt.Text & ...

Update sql command in vb.net flaws?

i have this code made by myself researching,
it returns no error, it update(s) some of the data entered in textboxes but not all the fields
i check the codes near the field that is updating to compare it to the textboxes that do not
update.
but i dont see the difference, it just not update all fields, only some fields
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim myCommand As SqlCommand
Try
'update command
sqlconn.Open()
myCommand = New SqlCommand(
"UPDATE tblOfficeEquipmentProfile SET OE_Category = '" & cmbCategory.Text
& "',OE_SubCategory = '" & cmbSubCategory.Text
& "', OE_Name = '" & txtName.Text
& "', OE_User = '" & txtUser.Text
& "', OE_Brand = '" & cmbBrand.Text
& "', OE_Model = '" & cmbModel.Text
& "', OE_Specs = '" & txtSpecs.Text
& "', OE_SerialNo = '" & txtSerialNo.Text
& "', OE_PropertyNo = '" & txtPropertyNo.Text
& "', OE_MacAddress = '" & txtMacAddress.Text
& "', OE_Static_IP = '" & txtStaticIp.Text
& "', OE_Vendor = '" & cmbVendor.Text
& "', OE_PurchaseDate = '" & txtPurchaseDate.Text
& "', OE_WarrantyInclusiveYear = '" & cmbWarrantyInclusiveYear.Text
& "', OE_WarrantyStatus = '" & txtWarrantyStatus.Text
& "', OE_Status = '" & txtStatus.Text
& "', OE_Dept_Code = '" & cmbDeptCode.Text
& "', OE_Location_Code = '" & cmbLocationCode.Text
& "', OE_Remarks ='" & cmbRemarks.Text
& "' WHERE OE_ID = '" & txtOEID.Text & "'", sqlconn)
' ^^ (edited to separate lines for ease of viewing )
myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Updated Records")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Some troubleshooting suggestions:
Try a pattern like this:
Dim SQL As String = "UPDATE STaff Set Initials='RCH' WHERE Initials = 'RCH'"
myCommand = New SqlCommand(SQL, sqlconn)
Dim iCnt As Integer = myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Updated " & iCnt & " Records")
Place a breakpoint on the second line and use the Text Visualizer to look at the SQL. You can also copy it and use in some other query tool to work on it and find the errors.
Also, capture the number of records changed (iCnt above) and do some QA and/or debug.
Injection: While your project may not be exposed to an injection attack you can step on your self by not making sure that the .Text values don't break the SQL. For example if any of the .Text contains an apostrophe the SQL will fail. You can write a Function to replace ' with '' and you'll be safe.
Or do each: OE_Location_Code = '" & cmbLocationCode.Text.replace("'","''")
This will convert "Fred's Room" to "Fred''s Room"

Getting text from text boxes on tab control

I have a form with a tabcontrol in it with 4 tabpages each has it's own texboxes and comboboxes, then I have a button outside of the tabcontrol wich builds a SQL string from all the values entered in these boxes even if some are left blank, the issue is that when i press the button i get a null reference exception and even when I use Try..Catch or on error resume next the compiler refuses to create the text string.
here is the code I have:
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
If Me.BankGuidTextBox.Text = vbNullString Then
Me.BankGuidTextBox.Text = Guid.Empty.ToString
End If
If Me.BankNumTextBox.Text = vbNullString Then
Me.BankNumTextBox.Text = 0
End If
If Me.NameTextBox.Text = vbNullString Or Me.CodeTextBox.Text = vbNullString Then
GoTo outofsub
End If
Try
Dim strSQL3 As String
strSQL3 = "USE MSILHR" & vbCrLf & _
"UPDATE employee SET Code = '" & Me.CodeTextBox.Text & "', Name = '" & Me.NameTextBox.Text & "', Latinname = '" & Me.LatinNameTextBox.Text & "', Barcode = '" & Me.BarcodeTextBox.Text & "', FirstName = '" & Me.FirstNameTextBox.Text & "', LastName = '" & Me.LastNameTextBox.Text & "', idFather = '" & Me.IdFatherTextBox.Text & "', idMother = '" & Me.IdMotherTextBox.Text & "', idBirthDate = '" & Me.IdBirthDateDateTimePicker.Text & "', idBirthplace = '" & Me.IdBirthPlaceTextBox.Text & "', idSex = '" & Me.IdSexComboBox.SelectedValue & "', idMaritalstat = '" & Me.IdMaritalstatComboBox.SelectedValue & "', idSmoker = '" & Me.IdSmokerComboBox.SelectedValue & "', idMilitary = '" & Me.IdMilitaryComboBox.SelectedValue & "', idRegistry = '" & Me.IdRegistryTextBox.Text & "', idNum = '" & Me.IdNumTextBox.Text & "', idAddress = '" & Me.IdAddressTextBox.Text & "', idNationality = '" & Me.IdNationalityTextBox.Text & "', idReligion = '" & Me.IdReligionComboBox.SelectedItem & "', idTel = '" & Me.IdTelTextBox.Text & "', idMobile = '" & Me.IdMobileTextBox.Text & "', idNotes = '" & Me.IdNotesTextBox.Text & "', jStartDate = '" & Me.JStartDateDateTimePicker.Text & "', jQuitDate = '" & Me.JQuitDateDateTimePicker.Text & "', jQuitReason = '" & Me.JQuitReasonTextBox.Text & "', jSocialSec = '" & Me.JSocialSecTextBox.Text & "', jSocialdin = '" & Me.JSocialdinDateTimePicker.Text & "', jSocialdout = '" & Me.JSocialdoutDateTimePicker.Text & "', jHoliday1 = '" & Me.JHoliday1ComboBox.SelectedValue & "', jHoliday2 = '" & Me.JHoliday2ComboBox.SelectedValue & "', jEmpStat = '" & Me.JEmpStatComboBox.SelectedValue & "', jEmail = '" & Me.JEmailTextBox.Text & "', jPrevvacs = '" & Me.JPrevvacsTextBox.Text & "', jAdminvacs = '" & Me.JAdminvacsTextBox.Text & "', jHealthvacs = '" & Me.JHealthvacsTextBox.Text & "', jUnpaidvacs = '" & Me.JUnpaidvacsTextBox.Text & "', DepartmentGuid = '" & Me.DepartmentGuidComboBox.SelectedValue.ToString & "', JobTitleGuid = '" & Me.JobTitleGuidComboBox.SelectedValue.ToString & "',SalarycalctypeGuid = '" & Me.SalarycalctypeGuidComboBox.SelectedValue.ToString & "', TeamGuid = '" & Me.TeamGuidComboBox.SelectedValue.ToString & "', WorkDays = '" & Me.WorkDaysTextBox.Text & "', DaHours = '" & Me.DaHoursTextBox.Text & "', OverTimeHourPrice = '" & Me.OverTimeHourPriceTextBox.Text & "', CutSalary = '" & Me.CutSalaryTextBox.Text & "',BasicSalary = '" & Me.BasicSalaryTextBox.Text & "', SpecialSalary = '" & Me.SpecialSalaryTextBox.Text & "',CurrencyGuid = '" & Me.CurrencyGuidComboBox.SelectedValue.ToString & "', BankGuid = '" & Me.BankGuidTextBox.Text & "', BankNum = '" & Me.BankNumTextBox.Text & "', PeriodGUID = '" & Me.EmpperiodCombo.SelectedValue.ToString & "'" & vbCrLf & _
"WHERE GUID = '" & Me.GUIDTextBox.Text & "'"
'"update employee set Picturepath = (select name from types where type = '660')+'\" & Me.NameTextBox.Text & "' where code = '" & Me.CodeTextBox.Text & "' AND Name = '" & Me.NameTextBox.Text & "'"
Dim dbConnection As New SqlConnection(connectionString)
' A SqlCommand object is used to execute the SQL commands.
Dim cmd As New SqlCommand(strSQL3, dbConnection)
' Open the connection, execute the command, and close the connection.
' It is more efficient to ExecuteNonQuery when data is not being
' returned.
dbConnection.Open()
cmd.ExecuteNonQuery()
dbConnection.Close()
MessageBox.Show("Record is updated.", _
"Data Addition Status", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch sqlExc As SqlException
MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
'Me.EmployeeTableAdapter.Fill(Me.MSILHRDataset.employee)
ResetUI()
outofsub:
MsgBox("you need to add more information!", MsgBoxStyle.Information, "Error")
End Sub
Ok new update :
I entered some data left some text boxes empty but made sure all combo boxes has values selected in them and then pressed updatebutton I got the same problem, but I redid that changed the current tab selected to any other one (from the other four) and then switched back to the previous tab, I press the button and IT WORKS!!?? it's as if the form doesn't Commit the values entered by user until focus changes or something it's crazy.
You are only catching a SqlException.
You need to also catch a general exception.
Catch sqlExc As SqlException
MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch exc As Exception
MessageBox.Show(exc.ToString, "General Exception Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Not sure why you are getting a null exception.
But it is not caught because it is not a SqlException.
On that String break it down do see where it is breaking.
On the surface it looks like it should work.
I suspect one of the controls is returning null rather than string.empty.