Syntax error in UPDATE statement vb 2010 - vb.net

i'm having trouble in my code. i just couldn't find the solution. When i run my program it always gives me an error
syntax error in UPDATE statement
here's the code.
Try
cmd.Connection = conn
cmd.CommandText = "UPDATE BC_Inventory SET [Price]='" + PriceU.Text + "',[Addition]='" + AddU.Text + "'," + _
"[Date_Updated]='" + DateU.Text + "',[Time_Updated]='" + TimeU.Text + "',[Updated_By]='" + UpdatedBy.Text + "'," + _
"WHERE [Item]='" + com_ItemU.Text + "'"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
Finally
conn.Close()
End Try
MsgBox("Inventory updated!")

You have added extra "," after [Updated_By] ([Updated_By]='" + UpdatedBy.Text + "'," <- extra ",") which is giving Syntax error

Please try this code
cmd.CommandText = "UPDATE BC_Inventory SET [Price]='" + PriceU.Text + "',[Addition]='" + AddU.Text + "'," + _
"[Date_Updated]='" + DateU.Text + "',[Time_Updated]='" + TimeU.Text + "',[Updated_By]='" + UpdatedBy.Text + "' " + _
"WHERE [Item]='" + com_ItemU.Text + "'"

Print your query out somehow before executing it, that's standard debugging 101.
That tends to solve 97.2% (a) of all SQL statement problems.
By that, I mean something like:
cmd.CommandText = "some hideously long and complex statement"
MessageBox (cmd.CommandText) ' Add this debug line temporarily'
cmd.ExecuteNonQuery()
In this particular case, it's the comma before the where clause.
(a) I just pulled this figure out of the ether. Actual results may vary, but I bet it'll fix more problems than not doing it :-)

Related

How to fix run time error 3075 through VBA MS ACCESS?

I am encountering a "Run-Time error 3075" with my code. I think I pretty much write the code right, the weird thing is, when I check the value of my variable, it's cut-off/shorten from what was supposed to be the full value of it, but when I tried outputting it in the "immediate window", it shows the full value.
I supposed to get all of this/my immediate window outputs this:
The quick brown fox jumps over the lazy dog.
But my variable only contains this:
The quick brown fox jumps o
The length of the real output that I'm trying to get is 611.
And then after this output, I'll get the "Run-Time Error 3075".
Here's a sample of my code:
Dim rs2 As DAO.Recordset
Set rs2 = CurrentDb.OpenRecordset("Select * FROM 2011_50K_ServiceText", dbOpenDynaset)
If DCount("*", "2011_50K_ServiceText") = 0 Then 'checks if table is empty
Else
rs2.MoveFirst
While rs2.EOF = False
i = i + 1
i2ndSetInterval = Format(i, "00")
s50KServiceText = rs2!Field1
If InStr(s50KServiceText, "See") > 0 Or InStr(s50KServiceText, "See") = 0 Then
If InStr(s50KServiceText, "See") = 0 Then
Else
s50KServiceText = Left(rs2!Field1, InStr(rs2!Field1, "See") - 1)
End If
sT = "50000"
sFrequency = CStr(getFrequencyInterval(sT))
sFrequency = sFrequency & "_" & CStr(i2ndSetInterval)
sLength = Len(s50KServiceText)
Debug.Print (s50KServiceText)
DoCmd.SetWarnings (WarningsOff)
DoCmd.RunSQL "INSERT INTO 2011_VehicleDistanceBased([Vehicle],[Frequency],[Service_Text]) values ('" + LabelVehicle.Caption + "', '" + sFrequency + "', '" + s50KServiceText + "')"
DoCmd.SetWarnings (WarningsOn)
End If
rs2.MoveNext
Wend
i2ndSetInterval = 0 'set it back to default
i = 0
rs2.Close
Set rs2 = Nothing
End If
Does anyone have any idea? It'll be much appreciated. Thank you
I got a database where some lastnames got single quotes, and we need them. In case you need the single quote, what worked for me was using single quotes twice, and that fixed everything.
So try s50KServiceText = Replace(s50KServiceText, "'", "''") in case you need to save the '.
NOTE: Please,note is not the same '' than ". That's why I said single quotes twice
I know there are different situation where this can occur but mine was solved when I found out that the value that I'm trying to fetch contains "single quote". The SQL clause causes an error because it reads it as well.
So the fixed that worked for me was this:
If InStr(s50KServiceText, "'") = 0 Then
Else
s50KServiceText = Replace(s50KServiceText, "'", "") <<<<--- this was the fixed
End If
DoCmd.SetWarnings (WarningsOff)
DoCmd.RunSQL "INSERT INTO 2011_VehicleDistanceBased([Vehicle],[Frequency],[Service_Text]) values ('" + LabelVehicle.Caption + "', '" + sFrequency + "', '" + s50KServiceText + "')"
DoCmd.SetWarnings (WarningsOn)
I hope it helps.

How to use sql command to update an sql table in vb.net?

I have the following SQL query which works in SQL server management :
Update SQLTableBlokke
set blokgemiddeld = ((tha_min4 + tha_min3 + tha_min2 +
tha_min1 + tha_huidig) /
NULLIF(((ABS(sign(tha_min4))+ABS(sign(tha_min3))+ABS(sign(tha_min2))+
ABS(sign(tha_min1))+ABS(sign(tha_huidig))) * 1.00),0))
As a beginner I have trouble using this command as a vb.net command. I have tried the following :
Dim konneksie As New SqlConnection
Dim opdraggem As New SqlCommand
konneksie.ConnectionString = "Data Source=GIDEON-E- LAPTOP\SQLEXPRESS2014;Initial Catalog=BlokwinsgewendheidDatabasis;Integrated Security=True"
konneksie.Open()
opdraggem.Connection = konneksie
opdraggem.CommandText = "Update(SQLTableBlokke)" & _
"blokgemiddeld = #((tha_min4 + tha_min3 + tha_min2 + tha_min1 + tha_huidig) / " & _
" NULLIF(((ABS(sign(tha_min4)) + ABS(sign(tha_min3)) + ABS(sign(tha_min2)) + ABS(sign(tha_min1)) + ABS(sign(tha_huidig))) * 1.0), 0)) "
opdraggem.ExecuteNonQuery()
However I get the error message : Additional information: Incorrect syntax near '('. The cursor stops at the opdraggem.ExecuteNonQuery() line.
I think I have to use parameters, but have no idea how to implement them.
Any help to a newbie would be much appreciated.
I don't see any need for you to use parameters in this case as you are not updating with any data not already in the table. Your CommandText should just be:
opdraggem.CommandText = "Update SQLTableBlokke" & _
"set blokgemiddeld = ((tha_min4 + tha_min3 + tha_min2 + " & _
"tha_min1 + tha_huidig) / " & _
"NULLIF(((ABS(sign(tha_min4))+ABS(sign(tha_min3))+ABS(sign(tha_min2))+ " & _
"ABS(sign(tha_min1))+ABS(sign(tha_huidig))) * 1.00),0))"
Your code will also benefit from a using statement on the connection as it will ensure the connection always gets closed. Demonstrated here:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx
Thank you all. Yes indeed I missed the keyword "Set".
Regards

VB6 SQL Type Mismatch issues with Databases

For my project, I have integrated a calculator which converts CM to FT. To make it worth more marks, I am trying to make it so that it will get the values and compare them against a Database to see which size Garage Door would be most suitable for the job
The SQL which purely searches for the value works. through and ADO which then only shows the found value on a data grid. But when I try to use the BETWEEN version, I get a Type Mismatch error which I have tried to fix by changing the variables to Integers and Reals, but it doesn't work. If anyone could help with this I would be really grateful!
Option Explicit
Dim sql As String
Dim sizeFindH As String
Dim sizeFindW As String
Dim sizeFindHUp As Double
Dim sizeFindHDown As Double
Dim sizeFindWUp As Double
Dim sizeFindWDown As Double
feet = 30.48
heightCm = txtHeightCm.Text
widthCm = txtWidthCm.Text
txtHeight.Text = heightCm / feet
txtWidth.Text = widthCm / feet
heightFt = txtHeight.Text
widthFt = txtWidth.Text
sizeFindH = txtHeight.Text
sizeFindW = txtWidth.Text
sizeFindHUp = sizeFindH + 1
sizeFindHDown = sizeFindH - 1
sizeFindWUp = sizeFindW + 1
sizeFindWDown = sizeFindW - 1
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.height) BETWEEN '" + "%" + sizeFindHDown + "%" + "') AND '" + "%" + sizeFindHUp + "%" + "');"
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.width) BETWEEN '" + "%" + sizeFindHDown + "%" + "') AND '" + "%" + sizeFindHUp + "%" + "');"
The error Type Mismatch highlights this line of code, as I'm sure it would the next if I could fix it.
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.height) BETWEEN '" + "%" + sizeFindHDown + "%" + "') AND '" + "%" + sizeFindHUp + "%" + "');"
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.width) BETWEEN '" + "%" + sizeFindHDown + "%" + "') AND '" + "%" + sizeFindHUp + "%" + "');"
The problem with your code in the SQL statement is that you are using an extra parentheses before the AND operator. It's not a logical operator here combining 2 conditions.. It's part of the BETWEEN clause and shouldn't have parentheses before. Also the % shouldn't be used here as others said.
Also the single quote is only used with strings.. So as long as your fields are numbers you shouldn't use it.
Oh.. And there's an extra parentheses without an opening one at the end of the query.
So your SQL should look like this:
sql = "SELECT * FROM garageDoorSize WHERE (garagedoorSize.width) BETWEEN " & sizeFindHDown & " AND " & sizeFindHUp & ";"
You are trying to concatenate a number and a string, hence the Type mismatch exception . Use CStr to convert the numbers to strings.
Also, I think you don't need the % signs, which are used with LIKE comparisons.
Also, as #jac correctly pointed out, use & to concatenate strings, not +. Edited my example to reflect for future readers of the post..
Try
sql = "SELECT * FROM garageDoorSize WHERE ((garagedoorSize.height) BETWEEN '" & CStr(sizeFindHDown) & "') AND '" & CStr(sizeFindHUp) & "');"
Note: Your code style of adding values direct to sql strings is vulnerable to sql injection (although not in this case as they are numbers). If these were strings, and came from user input your database and application is not secure. Best practice is to us sql parameter objects for your values... See this post, which shows usage. Note, first post I found, sure there are better guides out there :)

Using OleDb cannot insert into database

Additional information: Syntax error (missing operator) in query expression ''1')'.
This is my code
Dim connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= Database1.mdb;")
Dim command As New OleDbCommand("INSERT INTO Student_Enquiry (StudentID,Email,Receiver,Comment) VALUES('" + TextBox3.Text + "','" + TextBox1.Text + "','" + ComboBox1.Text + "', '" + TextBox4.Text + "')", connection)
command.Connection.Open()
command.ExecuteNonQuery()
command.Connection.Close()
The issue is that the final closing parenthesis in the insert statement actually isn't a normal Right Parenthesis; it is a different character.
You used ) - "Fullwidth Right Parenthesis", U+FF09
instead of ) - "Right Parenthesis", U+0029, ASCII 0x29
Compare the the invalid and the valid: ) != )
Use this instead:
Dim command As New OleDbCommand("INSERT INTO Student_Enquiry (StudentID,Email,Receiver,Comment) VALUES('" + TextBox3.Text + "','" + TextBox1.Text + "','" + ComboBox1.Text + "', '" + TextBox4.Text + "')", connection)
Also, you really shouldn't inject values into the query but rather use parametrized queries to avoid issues with potential SQL injection etcetera. The documentation shows you how to do this.

Data Type Mismatch error while updating Access database from VB.NET

cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Steve\Documents\Visual Studio 2010\Projects\Church Of Glory\Church Of Glory\Registry.accdb"
cmd.CommandText = "update Registry set relaship = '" + ComboBox3.Text + "',fathnam = '" + fathnam.Text + "',dob = '" & DateTimePicker1.Value & "',age = '" + age.Text + "',addr = '" + addr.Text + "',area = '" + areas.Text + "',city = '" + city.Text + "',zipc = '" + pinc.Text + "',conta = '" + cnct.Text + "',email = '" + email.Text + "',occup = '" + occu.Text + "',bap_stat = '" + bap_stat + "',bap_dat = '" & DateTimePicker2.Value & "',mar_stat = '" + mar_stat + "',mar_dat = '" & DateTimePicker3.Value & "',gen = 'Male' where fnam = '" + ComboBox2.Text + "' and lnam = '" + ComboBox1.Text + "'"
cmd.Connection = cn
cn.Open()
cmd.ExecuteNonQuery()
MsgBox("Update Successful")
cn.Close()
This code runs perfectly in my system.. but it says
oledb exception was unhandled "data type mismatch"
when i copied the code and executed it in my brother's computer.. i carefully changed the data source path... i'm just a beginner.. all the field type is text except for the dates.. i ve one more field which is an autonumber and i don want that in my update query.. so i left it..
It's more than likely something to do with the dates. No offence, but that code is very amateurish when it comes to updating a database table.
You should provide better conditioning for the dates; since you mention a difference with another computer, it's usually to do with the date/time formats being different between the two PCs. More common across countries, obviously, but check the date/time formats between the two computers in Control Panel to be sure.
Someone with access to a PC can probably supply a better answer!