How to solve issue with ExecuteNonQuery in VB.net - vb.net

This is my code for connection in form.load
cnn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DatabaseCasanova.mdb"
cnn.Open()
And this is my SQL statement:
If ClientNoTextBox.Text <> "" And FirstNameTextBox.Text <> "" And LastNameTextBox.Text <> "" And AddressTextBox.Text <> "" And ContactNumberTextBox.Text <> "" And ProductCodeTextBox.Text <> "" And ProductNameTextBox.Text <> "" And UnitTextBox.Text <> "" And PriceTextBox.Text <> "" And TotalPriceTextBox.Text <> "" Then
cmdinsert.CommandText = "INSERT INTO Orders(InvoiceNumber, ClientNo, FirstName, LastName, Address, ContactNumber, ProductCode, ProductName, Unit, Quantity, Price, TotalPrice, [DatePurchase], [DateToDeliver]) VALUES (" & Label4.Text & ", " & ClientNoTextBox.Text & ", '" & FirstNameTextBox.Text & "', '" & LastNameTextBox.Text & "', '" & AddressTextBox.Text & "', " & ContactNumberTextBox.Text & ", " & ProductCodeTextBox.Text & ", '" & ProductNameTextBox.Text & "', '" & UnitTextBox.Text & "', " & PriceTextBox.Text & ", " & TotalPriceTextBox.Text & ", '" & Label2.Text & "', '" & DateToDeliverDateTimePicker.Text & "')"
cmdinsert.CommandType = CommandType.Text
cmdinsert.ExecuteNonQuery()
MsgBox("ADDED")
ProductNameTextBox.Clear()
PriceTextBox.Clear()
FirstNameTextBox.Clear()
TotalPriceTextBox.Clear()
UnitTextBox.Clear()
LastNameTextBox.Clear()
AddressTextBox.Clear()
ClientNoTextBox.Clear()
ProductCodeTextBox.Clear()
QuantityTextBox.Clear()
ContactNumberTextBox.Clear()
Else
MsgBox("Complete your Transaction")
End If
cmdinsert.Dispose()
I don't know where is the problem because I try 5x to retype the SQL statement.
MS Access is my database and VB10 program

Related

Looping Code is not moving through the form

I have a form in my database that pulls data from a query to calculate the subassembly parts needed on a weekly basis and with the click of the "complete" button the required components should be moved into and out of inventory yet nothing happens when the complete button is clicked. The code should loop through and move all the parts but nothing happens.
I have stepped through to see if there are any errors and corrected a few syntax errors but that is all I have done.
Private Sub Command96_Click()
Dim ctl As Control
Dim ctln
Dim Qty As Double
Dim db As DAO.Database
Set db = CurrentDb
Dim rs As DAO.Recordset
For Each ctl In Me.Controls
Select Case TypeName(ctl)
Case "TextBox"
Select Case ctl.ControlName
Case ctl Like "*Q"
ctln = Me.Controls(Right(ctl, Len(ctl) - 1))
If Not IsNull(DLookup("[In]", "[Inventory]", "[PartNum] = '" & ctln & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "")) Then
num = DLookup("[In]", "[Inventory]", "[PartNum] = '" & ctln & "' AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "") + ctl
Else
num = ctl
End If
If Not IsNull(DLookup("[PartNum]", "[Inventory]", "[PartNum] = '" & ctln & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "")) Then
CurrentDb.Execute "UPDATE [Inventory] " _
& "SET [In] = " & num & " " _
& "WHERE [PartNum] = '" & ctln & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "", dbFailOnError
Else
CurrentDb.Execute "INSERT INTO [Inventory] " _
& "VALUES ('" & ctln & "'," & Me.YearNum & "," & Me.WeekNum & "," & num & ",0)", dbFailOnError
End If
num = 0
Set rs = db.OpenRecordset("SELECT UsedPartNum, (Quantity * " & ctl & ") AS Used FROM SubPartsUsed WHERE FinPartNum = '" & PartNum & "'", dbOpenDynaset)
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
Do Until rs.EOF = True
If Not IsNull(DLookup("[Out]", "[Inventory]", "[PartNum] = '" & rs!UsedPartNum & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "")) Then
num = DLookup("[Out]", "[Inventory]", "[PartNum] = '" & rs!UsedPartNum & "' AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "") + rs!Used
Else
num = rs!Used
End If
If Not IsNull(DLookup("[PartNum]", "[Inventory]", "[PartNum] = '" & rs!UsedPartNum & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "")) Then
CurrentDb.Execute "UPDATE [Inventory] " _
& "SET [Out] = " & num & " " _
& "WHERE [PartNum] = '" & rs!UsedPartNum & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & ""
Else
CurrentDb.Execute "INSERT INTO [Inventory] " _
& "VALUES ('" & rs!UsedPartNum & "'," & Me.YearNum & "," & Me.WeekNum & ",0," & num & ")"
End If
rs.MoveNext
Loop
End If
rs.Close
Set rs = Nothing
End Select
End Select
I expect the parts to be entered into inventory as complete subassembly parts and the components to make them should be removed from inventory.
Code is done by high professional specialist in VBA, many shortcuts for code executing. It could be difficult for new VBA programmer to correct this code, so I think:
first step should be adding Debug.Print code executed here at line number XXX in order to study what lines are executed, and if their execution is done as assumpted.
After that, if there is OK with code logic, Debug.Print all SQL statements, that are generated. So you can check their correctness through executing in query designer
E.g.:
Private Sub Command96_Click()
Dim ctl As Control
Dim ctln
Dim Qty As Double
Dim db As DAO.Database
Set db = CurrentDb
Dim rs As DAO.Recordset
Dim sSQL As String
For Each ctl In Me.Controls
Select Case TypeName(ctl)
Debug.Pring "looping through controls"
Case "TextBox"
Select Case ctl.ControlName
Case ctl Like "*Q"
Debug.Pring "Control with Q letter is found"
ctln = Me.Controls(Right(ctl, Len(ctl) - 1))
If Not IsNull(DLookup("[In]", "[Inventory]", "[PartNum] = '" & ctln & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "")) Then
Debug.Print "Num is DLookuped"
num = DLookup("[In]", "[Inventory]", "[PartNum] = '" & ctln & "' AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "") + ctl
Else
num = ctl
End If
If Not IsNull(DLookup("[PartNum]", "[Inventory]", "[PartNum] = '" & ctln & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "")) Then
Debug.Print "Executing Update Query for not null dlookup"
sSQL = "UPDATE [Inventory] " _
& "SET [In] = " & num & " " _
& "WHERE [PartNum] = '" & ctln & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & ""
Debug.Print sSQL
CurrentDb.Execute sSQL, dbFailOnError
Else
Debug.Print "Executing Update Query for null dlookup"
sSQL = "INSERT INTO [Inventory] " _
& "VALUES ('" & ctln & "'," & Me.YearNum & "," & Me.WeekNum & "," & num & ",0)"
Debug.Print sSQL
CurrentDb.Execute sSQL, dbFailOnError
End If
num = 0
Set rs = db.OpenRecordset("SELECT UsedPartNum, (Quantity * " & ctl & ") AS Used FROM SubPartsUsed WHERE FinPartNum = '" & PartNum & "'", dbOpenDynaset)
If Not (rs.EOF And rs.BOF) Then
Debug.Print "Beginning action for each record in PartNum select query"
rs.MoveFirst
Do Until rs.EOF = True
If Not IsNull(DLookup("[Out]", "[Inventory]", "[PartNum] = '" & rs!UsedPartNum & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "")) Then
Debug.Print "Executing Dlookup for element in PartNum select query"
num = DLookup("[Out]", "[Inventory]", "[PartNum] = '" & rs!UsedPartNum & "' AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "") + rs!Used
Else
num = rs!Used
End If
If Not IsNull(DLookup("[PartNum]", "[Inventory]", "[PartNum] = '" & rs!UsedPartNum & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & "")) Then
Debug.Print "Executing Update for not null DLookup element in PartNum select query"
sSQL = "UPDATE [Inventory] " _
& "SET [Out] = " & num & " " _
& "WHERE [PartNum] = '" & rs!UsedPartNum & "'AND [YearNum] = " & Me.YearNum & " AND [WeekNum] = " & Me.WeekNum & ""
Debug.Print sSQL
CurrentDb.Execute sSQL
Else
Debug.Print "Executing Update for null DLookup element in PartNum select query"
sSQL = "INSERT INTO [Inventory] " _
& "VALUES ('" & rs!UsedPartNum & "'," & Me.YearNum & "," & Me.WeekNum & ",0," & num & ")"
Debug.Print sSQL
CurrentDb.Execute sSQL
End If
rs.MoveNext
Loop
End If
rs.Close
Set rs = Nothing
End Select
End Select
In this case you should study your Immediate windows (openes by Ctrl + G) to see, what is the execution plan, and what SQL texts are generated, and check all of them.
Otherwise, there is too many your business specific logics in this code, and it is quite impossible to understand program behavior. Maybe such behavior is assumpted, due to business logics? Many, many questions
Hit the F9 key over, and over, and over, until you see what the problem is. Also, leverage 'Add Watch' to see what values are passed to which variables. That should help immensely. Finally, if this is done by a professional, why are you using: 'Command96_Click()'? Of course that's not the problem, but it's not helping either.

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.

Insert into statement error

Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jen\Documents\Jade\vb\database.accdb")
txtStatus.Text = "Active"
Dim account As String = ("Insert into Login(Username, Password, FirstName, LastName, AccountType, Status) VALUES ('" & txtUsername.Text & "' , '" & txtPass.Text & "', '" & txtFirst.Text & "', '" & txtLast.Text & "', '" & cmbType.Text & "', '" & txtStatus.Text & "')'")
conn.Open()
ole = New OleDbCommand(account, conn)
ole.ExecuteNonQuery()
MsgBox("Successfully Inserted!")
Dim strsql2 As New OleDbCommand("select * from Login", conn)
Dim sqlda = New OleDbDataAdapter(strsql2)
Dim sqldataset = New DataSet
sqlda.Fill(sqldataset)
Me.DataGridView1.DataSource = sqldataset.Tables(0)
conn.Close()
DataGridView1.Refresh()
an error shows that my insert into statement is incorrect. I already check my database many times and retype the code over but still get the same error.
I have Spotted an Extra (') qoute after closing bracket in query.Use this Query and Check
Dim account As String = ("Insert into Login(Username, Password, FirstName, LastName, AccountType, Status) VALUES ('" & txtUsername.Text & "' , '" & txtPass.Text & "', '" & txtFirst.Text & "', '" & txtLast.Text & "', '" & cmbType.Text & "', '" & txtStatus.Text & "')")
hope this helps.
Are AccountType and Status string type?
if not you should write this:
Dim account As String = ("Insert into Login(Username, Password, FirstName, LastName, AccountType, Status) VALUES ('" & txtUsername.Text & "' , '" & txtPass.Text & "', '" & txtFirst.Text & "', '" & txtLast.Text & "', " & cmbType.Text & ", " & txtStatus.Text & ")'")

Syntax error in UPDATE statement. via cmd.nonexecutequery

If Me.TextBox1.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO Table1(CandidateID, Fname, Mname, Lname, Partylist, Pst, course) " & _
" VALUES (" & Me.TextBox1.Text & ", '" & Me.TextBox2.Text & "', '" & Me.TextBox3.Text & "', '" & _
Me.TextBox4.Text & "', '" & Me.ComboBox1.Text & "', '" & Me.ComboBox2.Text & "', '" & Me.ComboBox3.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE table " & _
" SET CandidateID=" & Me.TextBox1.Text & _
", Fname='" & Me.TextBox2.Text & "'" & _
", Mname='" & Me.TextBox3.Text & "'" & _
", Lname='" & Me.TextBox4.Text & "'" & _
", Partylist='" & Me.ComboBox1.Text & "'" & _
", Pst='" & Me.ComboBox2.Text & "'" & _
", Course='" & Me.ComboBox3.Text & "'" & _
" WHERE CandidateID=" & Me.TextBox1.Tag
cmd.ExecuteNonQuery()
cmd.CommandText = "UPDATE Table1 " & _
" SET CandidateID=" & Me.TextBox1.Text & _
", Fname='" & Me.TextBox2.Text & "'" & _
", Mname='" & Me.TextBox3.Text & "'" & _
", Lname='" & Me.TextBox4.Text & "'" & _
", Partylist='" & Me.ComboBox1.Text & "'" & _
", Pst='" & Me.ComboBox2.Text & "'" & _
", Course='" & Me.ComboBox3.Text & "'" & _
" WHERE CandidateID=" & Me.TextBox1.Tag
cmd.ExecuteNonQuery()
my table was incorrect.
thank you for those who replied to my thread

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.