syntax error on edit button vb.net [closed] - sql

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Here is the code for my edit command. When I click the edit button message, a syntax error on the update statement pop up. But when debugging, there was no error.
Try
Dim SqlQuery As String = "UPDATE data SET archivedate = '" & txtarcdate.Text & "', filenumber = '" & txtfilenum.Text & "', filedate = '" & txtfiled.Text & "', section ='" & txtsection.Text & "', subject '" & txtsubject.Text & "' WHERE number = " & number & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record successfully updated.")
loadListView()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Here is your query statement:
Dim SqlQuery As String = "UPDATE data SET archivedate = '" & txtarcdate.Text & "', filenumber = '" & txtfilenum.Text & "', filedate = '" & txtfiled.Text & "', section ='" & txtsection.Text & "', subject '" & txtsubject.Text & "' WHERE number = " & number & ";"
Lets pay attention on this part:
& "', subject '" & txtsubject.Text &
You missed the equals sign. Should be:
& "', subject = '" & txtsubject.Text &
So the complete line would be:
Dim SqlQuery As String = "UPDATE data SET archivedate = '" & txtarcdate.Text & "', filenumber = '" & txtfilenum.Text & "', filedate = '" & txtfiled.Text & "', section ='" & txtsection.Text & "', subject = '" & txtsubject.Text & "' WHERE number = " & number & ";"
And finally, research about SQL injection. It is a serious security problem that your code are suffering.

Related

Syntax error in string in query expression in shortssize = S

Im updating an entry in MS Access using this code but it always returns an error. I dont know which part to correct. Please help me i cant seem to find which part is the error
Private Sub SaveChanges()
con.ConnectionString = OpenDBConnection()
con.Open()
Dim sql As String = "Update [JobOrderProd] set [CustomerOrderNumber] =
'" & CustomerOrderNumtxtbox.Text & "', [ItemNumber] = '" &
ItemNumbertxtbox.Text & "', [JerseyName] = '" &
JerseyNametxtbox.Text & "', [JerseyNumber] = '"`
& JerseyNumbertxtbox.Text & "', [JerseySize] = '" &
JerseySizetxtbox.Text & "',
[ShortsSize] = '" & ShortsSizetxtbox.Text
Dim cmd As New OleDbCommand(sql, con)`enter code here`
cmd.ExecuteNonQuery()`enter code here`
con.Close()
MsgBox("Entry for JO Production has been updated.")
ClearForm()
End Sub
I think you missed the single inverted comma in the end. add this to the end & "'"
JerseySizetxtbox.Text & "',
[ShortsSize] = '" & ShortsSizetxtbox.Text & "'"

Incorrect Syntax Near "("

So I was trying to do Update my database using buttons in VB.Net. I tried following different syntax in Updating tables but it still come up with the same error. It is so frustrating because we are running out of time to finish our system because of this. Please help me :'(
So this is my code wherein it will called after the button is clicked. What is wrong with my syntax here?
Public Sub UpdateClient(Client_ID As Integer, _ClientName As String, _Company_Add As String, _Email_Add As String,
_Tin_No As String, _Contact_Person As String, _Mobile_No As String, _Telephone_No As String,
_Remarks As String, _User As String)
Try
Dim strInsert As String = "UPDATE CLIENTS SET (ClientID = '" & Client_ID & "', ClientName = '" & _ClientName & "', Company_Add = '" & _Company_Add & "', Email_Add = '" & _Email_Add & "', Tin_No = '" & _Tin_No & "', Contact_Person = '" & _Contact_Person & "', Mobile_No = '" & _Mobile_No & "', Telephone_No = '" & _Telephone_No & "', Remarks = '" & _Remarks & "', User_ = '" & _User & "') WHERE (ClientID = '" & Client_ID & "') "
SQLCon.Open()
SqlCmd = New SqlCommand(strInsert, SQLCon)
SqlCmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Then here is my code on the button event:
Public Sub Update_Client()
SQL.UpdateClient(ClientIDLabel1.Text, txtCnamee.Text, txtCadd.Text, txtEadd.Text, txtTin.Text, txtCper.Text, txtMno.Text, txtTel.Text, txtRem.Text, User_Label1.Text)
End Sub
I'm pretty sure the error is in my sql string. What could it be? Please please help me :'(
P.s. I'm new to using VB.Net. Please bear with me :( Thank you.
Here is the immediate problem with your code: the syntax of UPDATE is as follows:
UPDATE <table> SET <field1>=<value1>, <field2>=<value2> ...
Note that the list of variables that you set is not enclosed in parentheses. You need to remove ( and ) from your parenthesized list to fix the syntax problem in your SQL:
Dim strInsert As String = "UPDATE CLIENTS SET ClientID = '" & Client_ID & "', ClientName = '" & _ClientName & "', Company_Add = '" & _Company_Add & "', Email_Add = '" & _Email_Add & "', Tin_No = '" & _Tin_No & "', Contact_Person = '" & _Contact_Person & "', Mobile_No = '" & _Mobile_No & "', Telephone_No = '" & _Telephone_No & "', Remarks = '" & _Remarks & "', User_ = '" & _User & "' WHERE (ClientID = '" & Client_ID & "') "
However, there is a much bigger problem: your program can be broken by =SQL injection attacks, which is very dangerous. You need to rewrite your SQL to accept parameters, and use parameterized SQL to fix this vulnerability. See an answer to this question for a quick example of how to parameterize your query.

Save when new record and update when edit on data occurs

I have my code for save button and update button but is there a way I can combine the two
commands in one button?
For example When I click 'SAVE/UPDATE Button' it will save on the database if it is a new record and it will rather update if the system found that there is already record on the database and save the edited data's
CODE FOR SAVE BUTTON
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Try
Dim myCommand As New SqlCommand
sqlconn.Open()
myCommand = New SqlCommand("INSERT INTO tblOfficeEquipmentProfile(OE_Category,OE_SubCategory,OE_ID,OE_Name,OE_User,OE_Brand,OE_Model,OE_Specs,OE_SerialNo,OE_PropertyNo,OE_MacAddress,OE_Static_IP,OE_Vendor,OE_PurchaseDate,OE_WarrantyInclusiveYear,OE_WarrantyStatus,OE_Status,OE_Dept_Code,OE_Location_Code,OE_Remarks) VALUES('" & cmbCategory.Text & "','" & cmbSubCategory.Text & "','" & txtOEID.Text & "','" & txtName.Text & "','" & txtUser.Text & "','" & cmbBrand.Text & "','" & cmbModel.Text & "','" & txtSpecs.Text & "','" & txtSerialNo.Text & "','" & txtPropertyNo.Text & "','" & txtMacAddress.Text & "','" & txtStaticIp.Text & "','" & txtVendor.Text & "','" & txtPurchaseDate.Text & "','" & txtWarrantyInclusiveYear.Text & "', '" & txtWarrantyStatus.Text & "','" & txtStatus.Text & "','" & cmbDeptCode.Text & "','" & cmbLocationCode.Text & "','" & txtRemarks.Text & "')", sqlconn)
myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Added")
sqlconn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
CODE FOR UPDATE BUTTON (NOTE: but still my update button has some error still trying to fix)
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim myCommand As New 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 = '" & txtVendor.Text & "', OE_PurchaseDate = '" & txtPurchaseDate.Text & "', OE_WarrantyInclusiveYear = '" & txtWarrantyInclusiveYear.Text & "', OE_WarrantyStatus = '" & txtWarrantyStatus.Text & "', OE_Status = '" & txtStatus.Text & "', OE_Dept_Code = '" & cmbDeptCode.Text & "', OE_Location_Code = '" & cmbLocationCode.Text & "', OE_Remarks ='" & txtRemarks.Text & "' WHERE OE_ID ='" & txtOEID.Text & "'", sqlconn)
Dim iCnt As Integer = myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Updated " & iCnt & " Records")
Catch ex As Exception
MsgBox(ex.Message)
End Try
You could create an enum that contains the state:
Enum DataState
Editing
Adding
None
End Enum
Then set a class-level variable:
private mDataState as DataState
Then set this according to whether you are adding or editing a record, then in the Save_Click subroutine, use an If-Then.
Write a stored procedure that checks to see if the record exists. If it does, update it. Otherwise, insert it.
Call this stored procedure from your vb.net code. Also, change your .net code so that it sends query parameters to your stored procedure.
Yours is a perennial favorite question here on SO: how to update an existing row or else insert it? And the answers are perennially wrong.
The standard SQL to do this does not have an if statement. The standard way is to insert the row subject to the constraint that it does not exist, and then update it:
insert into T values (...)
where not exists (
select 1 from T as t
where T.key = t.key
)
optionally check the rowcount and only update if it's 0
update T set ...
where T.key = value
If you don't check the rowcount from insert, the update is redundant.
It's better to put all that in a stored procedure but, even if you don't, you should be able to put both statements in one prepared statement, and attach that to one button in your GUI.

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.