Incorrect Syntax Near "(" - sql

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.

Related

Access 2016 Run time error invalid use of null

I am checking to see if a record exists in a Access 2016 form if it exist show a message if not add it to the database. But I am getting a invalid use of null when txtRepGrpNumber is empty, if not empty it adds it even though it already exists in the database. RepGrpNumber is a numeric field in the database. It errors out on my if statment.
Private Sub btnSave_Click()
Dim db As DAO.Database
Dim strSql As String
Dim message As String
Set db = CurrentDb
If Nz(CStr(Me.txtRepGrpNumber)) >= "" Then
strSql = "INSERT INTO dbo_TblSwShowRoom(RepGrpNumber, ViewOrder, RepCompany, AddressFull, Contact, Phone, Hours, ViewPhotos, ViewTour, ImageShow, Image, AddBy, DateAdded, DateChanged, ChangedBy, Enabled) " & _
"VALUES('" & Me.txtRepGrpNumber & "','" & Me.txtViewOrder & "', '" & Me.txtRepCompany & "', '" & Me.txtAddressFull & "', '" & Me.txtContact & "', '" & Me.txtPhone & "', '" & Me.txtHours & "', '" & Me.txtViewPhotos & "', '" & Me.txtViewTour & "', '" & Me.txtImageShow & "', '" & Me.txtImage & "', '" & Me.txtAddBy & "', '" & Me.txtDateAdded & "', '" & Me.txtDateChanged & "', '" & txtChangedBy & "', '" & txtEnabled & "')"
db.Execute strSql
Me.SubFrmSwShowRoom.Requery
Else
message = MsgBox("Cannot save because Group Number is Blank", vbCritical)
End If
'End If
Me.Requery
End Sub
If CStr(Nz(Me.txtRepGrpNumber,"")) <> "" Then
CStr can't convert a Null value. CStr(Null) throws the same error you're getting. This should do:
If Nz(Me.txtRepGrpNumber, vbNullString) <> vbNullString Then
The reason you are getting invalid use of null is if the value of txtRepGrpNumber has not been changed since you opened the form, and it was null, CStr throws the error invalid use of null when it gets to that.
To fix it:
If Me.txtRepGrpNumber & vbNullString <> vbNullString Then

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 & "'"

syntax error on edit button vb.net [closed]

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.

Trouble with updating database data

I'm having trouble with my UPDATE statement in which I'm trying to update table data through WHERE clause, which gives me error of data miss-match.
sqL = "UPDATE Customer SET name= '" & txtName.Text & "', adress= '" & txtAdress.Text & "', contact = '" & txtContact.Text & "' WHERE Customer_ID = '" & txtCustomerID.Text & "'"
I've also tried
sqL = "UPDATE Customer SET name= '" & txtName.Text & "', adress= '" & txtAdress.Text & "', contact = '" & txtContact.Text & "' WHERE Customer_ID = '" & Convert.ToInt32(txtCustomerID.Text) & "'"
with no luck.
Please use a parameterised query which is much cleaner and safer:
If you are on c#:
string sql = "UPDATE Customer SET name= #name, adress=#address, contact = #contact" +
" WHERE Customer_ID = #id";
using(SqlConnection conn = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#name",txtName.Text);
cmd.Parameters.AddWithValue("#address",txtAdress.Text);
cmd.Parameters.AddWithValue("#contact",txtContact.Text);
/*
NOTE: Make sure Textbox value is convertible to Customer_ID data type
before executing the query. It should be done before the using statement.
Use string.Trim() method to remove any space characters at start/end
*/
cmd.Parameters.AddWithValue("#id",txtCustomerID.Text.Trim());
conn.Open();
cmd.ExecuteNonQuery();
}
It looks like the data type of Customer_ID is an int. In that case, remove the single quotes from around your convert statement.
sqL = "UPDATE Customer SET name= '" & txtName.Text & "', adress= '" & txtAdress.Text & "', contact = '" & txtContact.Text & "' WHERE Customer_ID = " & Convert.ToInt32(txtCustomerID.Text)
But do double check the data type in your table to be sure.
Your query will not compile :-
The string concatenation operator in C# is plus sign not ampersand.
however as kaf advised always use parametrized queries.
Try using plus sign instead of an ampersand.
"UPDATE Customer SET name= '" + txtName.Text + "', adress= '" + txtAdress.Text + "', contact = '" + txtContact.Text + "' WHERE Customer_ID = '" + txtCustomerID.Text + "'"
If customer ID is int ,convert it to int .

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.