Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Public Sub openDB()
conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\VFMS_DB.mdb;" & "Jet OLEDB:System Database=Security.mdw;User ID=Adster;Password=300624;")
conn.Open()
End Sub
Public Function UpdateUser() As Integer
Dim retCode As New Integer
Try
openDB()
cmd = conn.CreateCommand()
The update command below keeps giving me this error: "Conversion from string "' WHERE [Username] = '" to type 'Double' is not valid." and I don't know why. The aUserName field is a String field and I checked to make sure it's populated.
cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & "', [Last Name] = '" & aSurname & "', [Contact Number] = '" & aContactNum & "', [Password] = '" & aPassword & "', [User Rights] = '" & aUserRights + "' WHERE [Username] = '" + aUserName + "' "
cmd.ExecuteNonQuery()
conn.Close()
'rsAddRecs = rsConn.Execute("UPDATE Users ([First Name], [Last Name], [Contact Number], [User Name], [Password], [User Rights]) VALUES ('" & aName & "','" & aSurname & "','" & aContactNum & "','" & aUserName & "','" & aPassword & "','" & aUserRights & "')")
retCode = 0
'rsConn.Close()
Return retCode
Catch ex As Exception
MessageBox.Show(ex.ToString, ex.Message, MessageBoxButtons.OK)
retCode = 1
Return retCode
End Try
End Function
You have a typo. You're using + concat characters at the end of the sql string instead of & characters
Wrong
cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & _
"', [Last Name] = '" & aSurname & _
"', [Contact Number] = '" & aContactNum & _
"', [Password] = '" & aPassword & "', [User Rights] = '" & _
aUserRights + "' WHERE [Username] = '" + aUserName + "' "
' ^ ^ ^
Right
cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & _
"', [Last Name] = '" & aSurname & _
"', [Contact Number] = '" & aContactNum & _
"', [Password] = '" & aPassword & "', [User Rights] = '" & _
aUserRights & "' WHERE [Username] = '" & aUserName & "' "
' ^ ^ ^
You SQL code uses [Username]:
cmd.CommandText = "UPDATE Users SET ... [Username]...
Whereas you commented out code used [User Name]:
'rsAddRecs = rsConn.Execute("UPDATE Users ... [User Name]...
Could the wrong column name be the source of the problem?
Another thought: have you sanitized your parameter values e.g. could the value contain a single quote that is upsetting the dynamic SQL. In any case, I think you should consider using prepared statements (or even PROCEDURES) and using Parameter objects to call the SQL, thereby deferring the sanitizing of the parameter values to the OLE DB provider, which will of course know more about the subject than you or I :)
Related
Trying to update table in ms Access using VBA but getting failed , used multiple option but table not getting updated
Dim bod As Date
Dim assets As String
Dim emname As String
Dim ecode As String
Dim Astatus As String
Astatus = "SOLD"
msaved = True
DoCmd.SetWarnings False
bod = Me.datetime.Caption
price1k = Me.cmbox1_1AID.Value
emname = Me.empname.Value
ecod = Nz(Me.code.Value, 0)
//tried using this but not getting updated no error
DoCmd.RunSQL "UPDATE [Asset E7450 List] SET Code = '" & ecod & "',[Date & Time] ='" & bod & "' ,Status ='" & Astatus & "',[Sold To] ='" & empname & "', where Asset-ID ='" & price1k & "'"
// Tried using this no update no error
CurrentDb.Execute "UPDATE [Asset E7450 List] SET Code = '" & ecod & "',[Date & Time] ='" & bod & "' ,Status ='" & Astatus & "',[Sold To] ='" & empname & "', where Asset-ID ='" & price1k & "'"
// Tried this method no data update no error
Dim strSQL As String
strSQL = "UPDATE [Asset E7450 List] SET Code = '" & ecod & "',[Date & Time] ='" & bod & "' ,Status ='" & Astatus & "',[Sold To] ='" & empname & "', where Asset-ID ='" & price1k & "'"
DoCmd.RunSQL strSQL
MsgBox " Booking Request Accepted ", vbInformation
If [Date & Time] is a date/time type field, use # delimiter instead of '. If field is a number type, don't use any delimiter.
Remove the comma in front of WHERE clause.
Need [ ] around Asset-ID field name because of the hyphen.
Advise not to use spaces nor punctuation/special characters in naming convention.
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.
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.
When running the program i get an error saying 'Data type mismatch in criteria expression.' and the line cmd.ExecuteNonQuery() is highlighted. In my database the datatype for 'ID' is AutoNumber and the datatype for 'Calories Burned' is decimal and everything else is text. I don't know if it is do with fact that when i input data into the text boxes its classed as a string. but if someone could help i would appreciate it a lot.
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim cmd As New OleDb.OleDbCommand
' add data to table '
If Not cnn.State = ConnectionState.Open Then
' open connection '
cnn.Open()
End If
cmd.Connection = cnn
If Me.txtID.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO [Training log] ([ID], [Runner Name], [Running Average Speed], [Cyclying Average Speed], [Swimming style] , [Calories Burned]) VALUES ('" & Me.txtID.Text & "' , '" & Me.txtRunnerName.Text & "' , '" & Me.txtRunSpeed.Text & "' , '" & Me.txtCycleSpeed.Text & "', '" & Me.txtSwimStyle.Text & "', '" & Me.txtCaloriesBurned.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE [Training log] SET ID=" & Me.txtID.Text & ", [Runner Name]='" & Me.txtRunnerName.Text & "', [Running Average Speed]='" & txtRunSpeed.Text & "', [Cyclyin Average Speed]='" & txtCycleSpeed.Text & "', [Swimming style]='" & txtSwimStyle.Text & "', [Calories Burned]='" & txtCaloriesBurned.Text & "' WHERE ID='" & txtRunnerName.Tag & "' "
cmd.ExecuteNonQuery()
End If
You may need to remove the single quotes around your non-string values.
cmd.CommandText = "INSERT INTO [Training log] ([ID], [Runner Name], [Running Average Speed], [Cyclying Average Speed], [Swimming style] , [Calories Burned]) VALUES (" & Me.txtID.Text & " , '" & Me.txtRunnerName.Text & "' , '" & Me.txtRunSpeed.Text & "' , '" & Me.txtCycleSpeed.Text & "', '" & Me.txtSwimStyle.Text & "', " & Me.txtCaloriesBurned.Text & ")"
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"