Vb.net with access database: How can you help me simplify these codes? - vb.net

this is my code:
'Set up connection string
Dim cnString As String
cnString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=..\data\testingDB.mdb"
Dim sqlQRY As String = "SELECT * " & _
"FROM users " & _
"WHERE firstName = '" & TextBox1.Text & "' " & _
" AND lastName = '" & TextBox2.Text & "'"
'Create connection
Dim conn As OleDbConnection = New OleDbConnection(cnString)
Try
' Open connection
conn.Open()
'create data adapter
Dim da As OleDbDataAdapter = New OleDbDataAdapter(sqlQRY, conn)
'create dataset
Dim ds As DataSet = New DataSet
'fill dataset
da.Fill(ds, "user")
'get data table
Dim dt As DataTable = ds.Tables("user")
'display data
Dim row As DataRow
If TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5) = 10 Then
MsgBox("10")
ElseIf TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5) = 9 Then
MsgBox("9")
ElseIf TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) Then
MsgBox("SUCCESS")
Else
MsgBox("fail")
End If
Catch ex As OleDbException
MsgBox("Error: " & ex.ToString & vbCrLf)
Finally
' Close connection
conn.Close()
End Try
I'm trying it to make it simple with the same results. As you can see the if-else statements were messy but it works 100%. I do want the if-else statements to be simple and works the same as above.

Edited to check value of row(5) for DbNull values
try this for if-else statements:
Dim row As DataRow = dt.Rows(0)
Dim r5 as Object = row(5)
If IsDbNull(r5) then r5 = 0
If TextBox1.Text = row(1) And TextBox2.Text = row(2) Then
Select Case r5
Case 10, 9 : MsgBox(r5)
Case Else : MsgBox("SUCCESS")
End Select
Else
MsgBox("fail")
End If

Dim cmd as New OledbCommand
Dim sqlQRY As String = "SELECT count(*) " & _
"FROM users " & _
"WHERE firstName = #fname " & _
" AND lastName = #lname"
cmd.parameters.add("#fname",TextBox1.Text)
cmd.parameters.add("#lname",TextBox2.Text)
Dim Cnt as Integer
cmd = new oledbcommand(sqlQRy,con)
Cnt = Convert.ToInt32( cmd.ExecuteScalar())
if Cnt>=1 then
msgbox("Success")
else if
msgbox("Failure")
end if

You must be aware that your SQL could logically return more than 1 row. You need to make sure that when you read data that you intend to test in this way, that your SQL uses a primary key and return 1 row only otherwise, problems could happen when more data is added. I suggest you first ensure that exactly 1 row is returned before you perform your if test (see my comment to #SenthilKumar). You need to send appropriate message to user when no rows are found and not perform the test.
If you get exactly 1 row back, you have to ensure that the data is not null (if applicable, this depends on how your columns are defined).
Remember that data that comes form UI could be padded with blanks or be in mixed case. You may need to watch for this.
Your IF statement is not too complex as is.I am not sure what you are testing exactly, but one can observe that you are using the following conditions:
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5)
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5)
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2)
You can see that the the expression
dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) is common. You can assign the value to a Boolean expression and use it in your test.
You also should not include non-database processing in the scope of your try.

Just more little simpler ..
If TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2)
MsgBox("SUCCESS - " & format(dt.Rows(0).Item(5)))
Else
MsgBox("fail")
End If

Related

VB.net and SQL .... For multiple read of database table

Im am currently coding an handsfree RFID attendance monitoring system where i could just swipe and record details automatically...
I've been in trouble about this piece of code where i need to fetch a table and another table inorder to check if there is an existing record in table1 as the details and table2 as a record in in/out. I wanted it as much as possible to be able to be in a 1 while loop
**
I kept getting this error **
Invalid attempt to access a field before calling Read()
`
Private Sub TextBox7_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox7.KeyDown
If e.KeyCode = Keys.Enter Then
'Dim idnum = Val(TextBox7.Text
Dim statu As String = ""
Dim idnum = (TextBox7.Text)
Dim record As String = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
ConnectToDB()
sql = "select * from rfidmaintest.student_details_dub where f9 = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
TextBox2.Text = (dr("f2"))
TextBox3.Text = (dr("f9"))
TextBox4.Text = (dr("f4"))
TextBox5.Text = (dr("f14"))
TextBox6.Text = (dr("f3"))
TextBox7.Clear()
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
**Invalid attempt to access a field before calling Read()**
If (dr("entry_record")) = String.Empty Then
status.Text = "IN"
End If
If status.Text = "IN" Then
status.Text = (dr("entry_record"))
record = "OUT"
ElseIf status.Text = "OUT" Then
record = "IN"
ElseIf status.Text = String.Empty Then
record = "IN"
End If
End While
dr.Close()
cn.Close()
`
I tried to call the table
You need another dr.read for the second query or you can use another reader, for example like dr2.read.
Your first While dr.read already closed with dr.close, you need to reopen the reader to continue to read the second query

if record exists update else insert sql vb.net

I have the following problem, I am developing a Clinic application using vb.net, the doctor has the ability to add medical information using checkboxes checkbox2.text = "Allergy" textbox15.text is the notes for Allergy, I want to insert the record if the patient's FileNo(Textbox2.text) doesn't exist, if it does then update the notes only, so far I was able to update it after 3 button clicks I don't know why????
any help is appreciated :)
thanks in advance
Dim connection3 As New SqlClient.SqlConnection
Dim command3 As New SqlClient.SqlCommand
Dim adaptor3 As New SqlClient.SqlDataAdapter
Dim dataset3 As New DataSet
connection3.ConnectionString = ("Data Source=(LocalDB)\v11.0;AttachDbFilename=" + My.Settings.strTextbox + ";Integrated Security=True;Connect Timeout=30")
command3.CommandText = "SELECT ID,Type FROM Medical WHERE FileNo='" & TextBox2.Text & "';"
connection3.Open()
command3.Connection = connection3
adaptor3.SelectCommand = command3
adaptor3.Fill(dataset3, "0")
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
For countz = 0 To count9
Dim A2 As String = dataset3.Tables("0").Rows(countz).Item("Type").ToString
Dim B2 As Integer = dataset3.Tables("0").Rows(countz).Item("ID")
TextBox3.Text = A2
If A2 = CheckBox1.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox22.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox1.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
ElseIf A2 = CheckBox2.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox15.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox2.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Next
Else
If CheckBox1.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox1.Text & "',N'" & TextBox22.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
If CheckBox2.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox2.Text & "',N'" & TextBox15.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
I think one of your problems may be related to your reducing the count of your table rows by 1 and then testing it above 0:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
Try changing to:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count
If count9 > 0 Then
Also, make sure one of the check-boxes (CheckBox1 or CheckBox2) mentioned later in your code is ticked.
-- EDIT --
Sorry - didn't explain why! The reason is that the majority of array/list like structures in .NET are zero based (i.e. start counting from 0 instead of 1).
The best course of action for you is to maximize your productivity by allowing SQL to do what it does best. Assuming you are using SQL Server 2008, the MERGE function is an excellent use case for the conditions that you have supplied.
Here is a very basic example that is contrived based upon some of your code:
CREATE PROCEDURE [dbo].[csp_Medical_Merge]
#MType int, #FileNo varchar(20), #MNotes varchar(max), #ID int, #OtherParams
AS
BEGIN
MERGE INTO [DatabaseName].dbo.Medical AS DEST
USING
(
/*
Only deal with data that has changed. If nothing has changed,
then move on.
*/
SELECt #MType, #MNotes, #FileNo, #ID, #OtherParams
EXCEPT
Select [Type], MNotes, FileNo, ID, OtherFields from [DatabaseName].dbo.Medical
) As SRC ON SRC.ID = DEST.ID
WHEN MATCHED THEN
UPDATE SET
DEST.MNOTES = SRC.MNOTES,
DEST.FileNo = SRC.FileNo,
DEST.Type = SRC.Type
WHEN NOT MATCHED BY TARGET THEN
INSERT (FieldsList)
VALUEs (FileNo, MNotes, etc, etc);
END
GO

Search through the database using a combobox, if an item is in a database, prompt will appear

Good day everyone.
I'm making a POS and Inventory Management System and I'm having a problem with this particular module as of now.
When adding an item to purchase order list, if an item is already in the purchaseorder database, the system will prompt that there is already a pending order. I've done the prompt, but the adding to the database was kinda messed up. It doesn't do a thing at all. The code there is working when I remove the ds.hasrows and while dr.read conditions. This is my code:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Ceiling = CInt(txtCeiling.Text)
TotalQuantity = CurrentItemQuantity + CInt(txtPurchaseQty.Text)
If TotalQuantity > Ceiling Then
MsgBox("Exceeds Ceiling Point.")
Else
sqlString = "SELECT PRODUCT_ID FROM posinventory.purchaseorder WHERE purchaseorder.PRODUCT_ID = '" & cboProductID.Text & "'"
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
If CurrentItem = dr.Item("PRODUCT_ID") Then
MsgBox("Product has pending order.")
cboProductID.Focus()
Else
sqlString = "INSERT INTO posinventory.purchaseorder (PRODUCT_ID, PURCHASE_QUANTITY, DATE_PURCHASED, TIME_PURCHASED) VALUES (" & cboProductID.Text & ", '" & txtPurchaseQty.Text & "', '" & txtDate.Text & "', '" & txtTime.Text & "')"
Try
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
dr.Close()
Catch ex As Exception
MsgBox("Error saving to database. Error is: " & ex.Message)
Exit Sub
End Try
MsgBox("Transaction Complete.")
lvOrderList.Items.Clear()
sqlString = "SELECT posinventory.purchaseorder.TRANSACTION_ID, posinventory.products.PRODUCT_ID, posinventory.products.PRODUCT_NAME, posinventory.products.SUPPLIER_NAME, posinventory.purchaseorder.PURCHASE_QUANTITY, posinventory.purchaseorder.DATE_PURCHASED, posinventory.purchaseorder.TIME_PURCHASED FROM posinventory.purchaseorder, posinventory.products WHERE posinventory.purchaseorder.PRODUCT_ID = posinventory.products.PRODUCT_ID"
cmd = New MySqlCommand(sqlString, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcol(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcol)
Me.lvOrderList.Items.Add(lvi)
Next
grpCreateOrder.Enabled = False
grpOrderList.Enabled = True
cboProductID.SelectedIndex = -1
txtPurchaseQty.Text = ""
txtDate.Text = ""
txtTime.Text = ""
txtProductName.Text = ""
txtSupplier.Text = ""
txtQty.Text = ""
txtCeiling.Text = ""
btnBack.Enabled = True
End If
End While
End If
dr.Close()
End If
End Sub
I think its because you are inside of a loop using a cmd and dr. While you are in there you are then defining a new cmd and dr.
Try using different names eg cmd2, dr2.

SQL to search for encrypted values not working

I am using a button to trigger a SELECT statement, and based off of the criteria the user enters in 2 text boxes (SearchFirstTxt, SearchLastTxt), I send the Text values of those text boxes through an encryption class to find their match
I return them in a SqlDataAdapter and use it to fill a DataTable. I then use DataGridView.DataSoruce = dt to add it to the DGV.
My question: If the user leaves both text boxes blank and clicks the "SearchBtn", it doesn't select all of the records. It actually only selects records with the same encrypted values.
Here is the code:
eFirst = clsEncrypt.EncryptData(SearchFirstTxt.Text.Trim.ToUpper)
eLast = clsEncrypt.EncryptData(SearchLastTxt.Text.Trim.ToUpper)
conn.Open()
cmd.Connection = conn
If SearchFirstTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = '" & eLast & "' ; "
ElseIf SearchLastTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = '" & eFirst & "' ; "
Else
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
End If
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
DataGridView1.DataSource = dt
Try
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("FIRST_NM_TXT") = clsEncrypt.DecryptData(eFirst)
dt.Rows(i)("LAST_NM_TXT") = clsEncrypt.DecryptData(eLast)
Next
Catch ex As Exception
MessageBox.Show("Error")
Finally
conn.Close()
End Try
How can I select ALL of the records from the Participant dbo?
The result set looks like this if the text boxes are left blank:
Edit: I switched my code, and it retrieves ALL of the results, however, now I am having difficulty returning them. (They return as encrypted, but not decrypted)
Here are the changes:
If SearchFirstTxt.Text = "" And SearchLastTxt.Text = "" Then
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
ElseIf SearchLastTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = '" & eFirst & "' ; "
ElseIf SearchFirstTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = '" & eLast & "' ; "
End If
If I understand your requirements correctly, you need to add a check for the other search text when you try to search your encrypted data
If SearchFirstTxt.Text = "" AndAlso SearchLastTxt.Text <> "" Then
' Search the last only if you have a last and not a first'
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = #searchLast"
cmd.Parameters.AddWithValue("#searchLast", eLast)
ElseIf SearchLastTxt.Text = "" AndAlso SearchFirstTxt.Text <> "" Then
' Search the first only if you have a first and not a last'
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = #searchFirst"
cmd.Parameters.AddWithValue("#searchFirst", eFirst)
ElseIf SearchFirstTxt.Text = "" AndAlso SearchLastText.Text = "" Then
' Both emtpy so search everything'
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
Else
' Both filled so search exactly (not sure if this is needed)'
cmd.CommandText = "Select * FROM Participant " & _
"WHERE FIRST_NM_TXT = #searchFirst " & _
"OR LAST_NM_TXT = #searchLast"
cmd.Parameters.AddWithValue("#searchFirst", eFirst)
cmd.Parameters.AddWithValue("#searchLast", eLast)
End If
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
Notice that I have removed your string concatenation and used a parameterized query. It is safer (avoids Sql Injection) and remove parsing problems (what if your encrypted text contains a single quote?)
Supposing then that you want to show the decrypted data you apply your deCryptData function to the values in the datatable, not to the same values used for the search (you already know the clear text)
Try
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("FIRST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("FIRST_NM_TXT").ToString)
dt.Rows(i)("LAST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("LAST_NM_TXT").ToString)
Next
Catch ex As Exception
MessageBox.Show("Error")
Finally
conn.Close()
End Try

I am getting Error "There is no row at position 0" from code below

Private Sub Button3_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If txtID.Text = "" Then
MsgBox("Please input a valid Employee code to load a corresponding record", MsgBoxStyle.Information)
Else
dbProvider = "Provider=Microsoft.Ace.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Blessing\Documents\IBCARIP.accdb;Persist Security Info=False"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "select * from Calculator where " _
& "EmpCode = " & " '" & txtID.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "IBCARIP")
lblSAI.Text = ds.Tables("IBCARIP").Rows(inc).Item("SName") & ds.Tables("IBCARIP").Rows(inc).Item("FName")
lblRate.Text = ds.Tables("IBCARIP").Rows(inc).Item("NRate")
lblOT.Text = ds.Tables("IBCARIP").Rows(inc).Item("OTRate")
lblBnk.Text = ds.Tables("IBCARIP").Rows(inc).Item("BName") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("ANumber") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("AType")
con.Close()
ds.Tables("IBCARIP").DataSet.Clear()
MaxRows = ds.Tables("IBCARIP").Rows.Count
'inc = 0
End If
End Sub
The message comes when i enter a wrong or non-existent Employee code in txtID.text
how can i solve tha problem
try as below
you should always check dataset table and rows count
i am not much familiar with vb .net(i am in C#) but i think following is good to go
If txtID.Text = "" Then
MsgBox("Please input a valid Employee code to load a corresponding record", MsgBoxStyle.Information)
Else
dbProvider = "Provider=Microsoft.Ace.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Blessing\Documents\IBCARIP.accdb;Persist Security Info=False"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "select * from Calculator where " _
& "EmpCode = " & " '" & txtID.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "IBCARIP")
If ds.Tables.Count > 0 AndAlso ds.Tables("IBCARIP").Rows.Count >0 Then
lblSAI.Text = ds.Tables("IBCARIP").Rows(inc).Item("SName") & ds.Tables("IBCARIP").Rows(inc).Item("FName")
lblRate.Text = ds.Tables("IBCARIP").Rows(inc).Item("NRate")
lblOT.Text = ds.Tables("IBCARIP").Rows(inc).Item("OTRate")
lblBnk.Text = ds.Tables("IBCARIP").Rows(inc).Item("BName") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("ANumber") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("AType")
con.Close()
ds.Tables("IBCARIP").DataSet.Clear()
MaxRows = ds.Tables("IBCARIP").Rows.Count
'inc = 0
End if
End If
End Sub
First the most important: you are open for SQL-Injection since you are not using sql-parameters but concatenating the query with user input.
The reason for the error is that you are trying to access the a DataRow in the DataTable without checking if there is at least one. But you are accessing the row with index inc, maybe the table does not contain so many rows. Why do you use a variable at all here?
da.Fill(ds, "IBCARIP")
If ds.Tables("IBCARIP").Rows.Count = 0 Then Return ' or something else
' here you can safely access the first row...
Here the long version with parameters:
Using con = New OleDbConnection(dbProvider & dbSource)
Dim sql = "select * from Calculator where EmpCode=?"
Using da = New OleDbDataAdapter(sql, con)
da.SelectCommand.Parameters.AddWithValue("#EmpCode", txtID.Text)
da.Fill(ds, "IBCARIP")
If ds.Tables("").Rows.Count > 0 Then
Dim row = ds.Tables("IBCARIP").Rows(0)
Dim SName = row.Field(Of String)("SName")
Dim FName = row.Field(Of String)("FName")
Dim sai = String.Format("{0}{1}", SName, FName)
lblSAI.Text = sai
' ... '
End If
End Using
End Using