Validate SQL data and check for Null - sql

I have a textbox(txtOrderNum) where you enter an 'order' number and update a 'userfield' based on a date that is generated in another textbox(txtDate), I want to validate that the 'order' number entered matches the 'Order' number in the database, then update 'UserField1' only if its NULL, if it doesn't match then do nothing.
My goal, I don't want to overwrite data that is already in the Userfield1, and I want to ensure I update the correct 'Order' number that exist.
****I've updated my code based on suggestion below, I just need to validate if 'Order' number exist AND matches the order number entered in the textbox, then run update query. (also need to parameterized the query, I have some ideas but could use some help)****
Public Sub executequery(ByVal query As String)
Try
Dim cmd As New SqlCommand(query, conn)
conn.Open()
If (conn.State = ConnectionState.Open) Then
cmd.ExecuteNonQuery()
conn.Close()
Else
MessageBox.Show("Check Connection")
conn.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
Return
Finally
conn.Close()
End Try
End Sub
'My call Event via Enter Key within Textbox (txtOrdernum)
Dim conn As New SqlConnection("My data source")
Try
Dim updatequery As String = ("UPDATE [DATA].[dbo].[Order] SET [Userfield1] = '" & txtDate.Text.Trim() & "' WHERE [order] ='" & txtOrdernum.Text.Trim() & "' AND [Userfield1] IS NULL")
If e.KeyChar = Chr(13) Then 'Chr(13)
If txtOrdernum.Text.Length >= 8 Then
'MessageBox.Show(updatequery)
executequery(updatequery)
Else
MessageBox.Show("Invalid Order Number'")
End If
Catch ex As Exception
MsgBox(ex.ToString)
Return
End Try

As N0Alias stated, add "AND [UserField1] IS NULL".
Just be careful with the way you build your query. Building one like your example can allow SQL injection.
You should use the 'SqlCommand.Parameters' property to add values into your query.

Related

Is there a way to avoid getting an error when I use one of two textboxes to search from database?

I have two textboxes that I can use to search from database but it is not all the time when I use two textboxes to search.
Sometimes I use one but when i do so I get an error:
"Syntax error missing operator in query expression"
because the other textbox is empty. This only happens when I am using >=.
It seems to want all textboxes to have text.
Sub search()
Try
DataGridRecords.Rows.Clear()
conn.Open()
Dim cmd As New OleDb.OleDbCommand("Select * from tblDies where `IDSIZE` >= " & txtIdSize.Text & " OR `ODSIZE` >= " & txtOdSize.Text & " ", conn)
dr = cmd.ExecuteReader
While dr.Read
DataGridRecords.Rows.Add(dr.Item("ID"), dr.Item("DIENUMBER"), dr.Item("DESCRIPT"), dr.Item("OLDNUMBER"), dr.Item("CODE"), dr.Item("QUANTITY"), dr.Item("IDSIZE"), dr.Item("ODSIZE"), dr.Item("HEIGHT"), dr.Item("FLANGE HT"), dr.Item("FLANGE DIA"), dr.Item("CuRef"), dr.Item("CUTEL"), dr.Item("CuContact"), dr.Item("Price-selling"), dr.Item("P/no"), dr.Item("Stoksize"), dr.Item("Material"), dr.Item("Shore"), dr.Item("DieChkd"), dr.Item("DIECOST"), dr.Item("DATE"), dr.Item("REMARKS"), dr.Item("PRREF"))
End While
dr.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub

how can i push a msgbox if record is not found in Database using vb.net

seeking help how i can push a msgbox error if a record is not in the database or no data in the database. im using vb.net and sql to check the record. not sure how to do,
here is my code
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
'Main.BGCPnl.Visible = True
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
//>Here is my code for the error message when record is not
found, im not sure what will be the right code.
i used count parameter
BGCEmp = dr(ADS.UserEmpID)
If BGCEmp.Count = 0 Then
MsgBox("no record")
Exit Sub
End If
End While
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
You should learn how to properly use the Read method and the HasRows property of your data reader. If there can never be more than one record but there might be none then use just Read:
If myDataReader.Read() Then
'There is a row and you can access its data here.
Else
'There are no rows.
End If
If there may be multiple rows and either there can't be no rows or you don't need to do anything specific in the case that there are no rows then just use Read:
While myDataReader.Read()
'Access the current row here.
End While
If there are no rows then you never enter the loop and execution simply continues after that.
If there may be zero, one or more rows and you do need to do something specific in the case where there are none, use both HasRows and Read:
If myDataReader.HasRows Then
'There is at least one row so read the data.
While myDataReader.Read()
'Access the current row here.
End While
Else
'There are no rows.
End If
There may be situations where you only care whether there is data but you don't need the data itself. In that case, just use HasRows:
If myDataReader.HasRows Then
'There is a at least one row
Else
'There are no rows.
End If
In cases like that though, I'd suggest that you should be doing something like using a COUNT function in your query and calling ExecuteScalar rather than calling ExecuteReader.
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
End While
Else
MessageBox.Show("No Record found", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
Read documentation about Read() and HasRows.

Data mismatch in criteria expression in delete oledb command

I'm simply putting the Oledb command code for delete but the problem is when I delete one of the data from the DGV and there's a message of Data type miss match in criteria expression. Here's the one of my screen shots in this problem:
Below was the codes here:
Dim com = New OleDbCommand("DELETE FROM CustInfo WHERE Customer_ID = '" & Me.Txt_CusID.Text & "'", con)
Try
com.ExecuteNonQuery()
MsgBox("Delete : SUCCESS!")
Me.Close()
ShowTable()
Txt_CusID.Text = ""
Txt_Full.Text = ""
Txt_Add.Text = ""
Txt_Con.Text = ""
Txt_Email.Text = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Could you tell me about this problem or lacking something as soon as possible to run this command?

Display SQL Result in label?

Dim invoiceCount As String =
"SELECT COUNT(CustomerID) " &
"FROM Invoices " &
"WHERE CustomerID = #customerID"
Dim selectCount As New OleDbCommand(invoiceCount, connection)
selectCount.Parameters.AddWithValue("#customerID", customerID)
Try
connection.Open()
Dim reader2 As OleDbDataReader = selectCount.ExecuteReader(CommandBehavior.SingleRow)
If reader2.Read Then
frmCustomerMaintenance.lblIncidents.Text = 'what do I put here?
End If
reader2.Close()
Catch ex As OleDbException : Throw ex
Finally : connection.Close()
End Try
I've been messing with this for a while now and everything I try returns an error. I'm still fairly new to SQL in general but this needs to be done. I just want to store the result of the query in a label to show how many records the customer entered has..
Well, to read the first column, you can just do this:
frmCustomerMaintenance.lblIncidents.Text = reader.GetValue(0).ToString()
However, when you are only reading a single column from a single row, like that, it's easier to just call ExecuteScalar instead of ExecuteReader:
frmCustomerMaintenance.lblIncidents.Text = selectCount.ExecuteScalar().ToString()
This is what you are searching for:
frmCustomerMaintenance.lblIncidents.Text = reader2[0].ToString()

Code does not work but has no errors

I'm working on an information system and here's my syntax for update, it shows no errors, but it does not update my table. Anyone can help on this matter?
By the way, I'm using VB.Net 2010 and MS Access 2007.
Try
Dim conn As New OleDbConnection(gConnectionString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
Dim comm As New OleDbCommand( "UPDATE PropertiesPayors SET [PayorName]=#PayorName,[LotNumber]=#LotNumber,[LotArea]=#LotArea,[DateOfAward]=#DateOfAward,[DateDueForFullPayment]=#DateDueForFullPayment,[PurchasePrice]=#PurchasePrice,[ReAppraisedValue]=#ReAppraisedValue,[AmountDue]=#AmountDue,[TotalAmountPaid]=#TotalAmountPaid,[AmountUnpaid]=#AmountUnpaid,[PropertyRemarks]=#PropertyRemarks WHERE [PropertyID]=#PropertyPayorID ", conn)
With comm
With .Parameters
.AddWithValue("#PropertyPropertyID", Val(propertyPayorSessionID.ToString))
.AddWithValue("#PayorName", txtPayorName.Text)
.AddWithValue("#LotNumber", txtLotNumber.Text)
.AddWithValue("#LotArea", Val(txtLotArea.Text))
.AddWithValue("#DateOfAward", txtDateOfAward.Text.ToString)
.AddWithValue("#DateDueForFullPayment", txtDateOfFullPayment.Text.ToString)
.AddWithValue("#PurchasePrice", Val(txtPurchasePrice.Text))
.AddWithValue("#ReAppraisedValue", Val(txtReAppraisedValue.Text))
.AddWithValue("#AmountDue", Val(txtAmountDue.Text))
.AddWithValue("#TotalAmountPaid", Val(txtTotalAmountPaid.Text))
.AddWithValue("#AmountUnpaid", Val(txtAmountUnpaid.Text))
.AddWithValue("#PropertyRemarks", txtRemarks.Text)
End With
.ExecuteNonQuery()
End With
msg = MsgBox("Record Updated.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Update Payor")
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Query Error")
End Try
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Connection Error")
End Try
You just have a typo on your code
Replace
#PropertyPropertyID
with
#PropertyPayorID
then arrange your parameter order same as your update statement.
And try this :
Try
Dim conn As New OleDbConnection(gConnectionString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
Dim comm As New OleDbCommand("UPDATE PropertiesPayors SET [PayorName]=#PayorName,[LotNumber]=#LotNumber,[LotArea]=#LotArea,[DateOfAward]=#DateOfAward,[DateDueForFullPayment]=#DateDueForFullPayment,[PurchasePrice]=#PurchasePrice,[ReAppraisedValue]=#ReAppraisedValue,[AmountDue]=#AmountDue,[TotalAmountPaid]=#TotalAmountPaid,[AmountUnpaid]=#AmountUnpaid,[PropertyRemarks]=#PropertyRemarks WHERE [PropertyID]=#PropertyPayorID ", conn)
With comm
With .Parameters
'.AddWithValue("#PropertyPayorID", Val(propertyPayorSessionID.ToString)) move this to the last part
.AddWithValue("#PayorName", txtPayorName.Text)
.AddWithValue("#LotNumber", txtLotNumber.Text)
.AddWithValue("#LotArea", Val(txtLotArea.Text))
.AddWithValue("#DateOfAward", txtDateOfAward.Text.ToString)
.AddWithValue("#DateDueForFullPayment", txtDateOfFullPayment.Text.ToString)
.AddWithValue("#PurchasePrice", Val(txtPurchasePrice.Text))
.AddWithValue("#ReAppraisedValue", Val(txtReAppraisedValue.Text))
.AddWithValue("#AmountDue", Val(txtAmountDue.Text))
.AddWithValue("#TotalAmountPaid", Val(txtTotalAmountPaid.Text))
.AddWithValue("#AmountUnpaid", Val(txtAmountUnpaid.Text))
.AddWithValue("#PropertyRemarks", txtRemarks.Text)
.AddWithValue("#PropertyPayorID", Val(propertyPayorSessionID.ToString))
End With
.ExecuteNonQuery()
End With
msg = MsgBox("Record Updated.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Update Payor")
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Query Error")
End Try
Catch myError As Exception
MsgBox("Error: " & myError.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Connection Error")
End Try
This will solve your problem.
see also: OleDbCommand parameters order and priority for reference.
Best Regards!
If I remember correctly, by default, there is no relation between the name of the place holders in the query and the name of the parameters. As BizApps has said, you should place your parameters in the same order as defined in your query; which means that PropertyPayorID should come last when you add it to your Parameters collection. The names for the Parameters collection are to be used only locally; like for changing some properties of the individual parameters.
Also, I don't remember if you can use named parameters in your query string as a place holder or if you must use a ? instead; something like Update PropertiesPayors SET [PayorName]=?, ...
The command statement .ExecuteNonQuery returns the number of rows which were affected.
This means if you used...
intRowsAffected = .ExecuteNonQuery()
And the value returned into the variable intRowsAffected was ZERO (0)
Then that means a record with the same value for your field PROPERTYID (meaning the value you passed into the parameters collection... PROPERTYPAYORSESSIONID) does not exist!
And thats why you are not recieving any errors and nor is your database being updated.
To double check this...
Where your code statement .EXECUTENONQUERY() is...
You can replace it with the following...
intRowsAffected = .ExecuteNonQuery()
Messagebox(intRowsAffected & " Data rows were updated.")
If the messagebox shows zero rows were updated (no rows were updated) then your next step would be to MANUALLY check the database and see if the row ACTUALLY exists and if it has the SAME key value that you are using to identify the row - which I assume is the property-payor-session-id.
Also keep in mind that the session-id is apt to change with each session and not static all the time.