I am trying to set employees for a company to 'present' if they clock-in/out on the program. The database has a field with the same name and uses a boolean value to store whether someone is or isn't present. I believe my SQL statement is correct. The issue that I continue to get is: "Additional information: No value given for one or more required parameters."
Here is the code that I am using to perform the UPDATE query:
Private Sub btnClockout_Click(sender As Object, e As EventArgs) Handles btnClockout.Click
'SelectedEmployee = lstClockin.FocusedItem.Text
'lblClockinStatusColor.BackColor = Color.Red
'btnClockout.Enabled = False
'btnClockin.Enabled = True
'lblClockinStatus.Text = "Employee is: Clocked Out"
'If txtInfoEmployeeID.Text = "" Then
' MsgBox("You need to select a employee to clock-out.", MsgBoxStyle.Exclamation)
'End If
con.ConnectionString = provider & datafile
con.Open()
sqlstatement = ("UPDATE [EmployeeAccounts] SET [Present] = False WHERE [EmployeeID] = '" & SelectedEmployee & "'")
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "ClockOutButton")
con.Close()
End Sub
I don't think there is any Boolean type in SQL database. You can use below code.
Private Sub btnClockout_Click(sender As Object, e As EventArgs) Handles btnClockout.Click
SelectedEmployee = lstClockin.FocusedItem.Text
'lblClockinStatusColor.BackColor = Color.Red
'btnClockout.Enabled = False
'btnClockin.Enabled = True
'lblClockinStatus.Text = "Employee is: Clocked Out"
'If txtInfoEmployeeID.Text = "" Then
' MsgBox("You need to select a employee to clock-out.", MsgBoxStyle.Exclamation)
'End If
con.ConnectionString = provider & datafile
con.Open()
sqlstatement = ("UPDATE [EmployeeAccounts] SET [Present] = 'False' WHERE [EmployeeID] = '" & SelectedEmployee & "'")
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "ClockOutButton")
con.Close()
End Sub
Related
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
Private Sub BTNupdate_Click(sender As Object, e As EventArgs) Handles BTNupdate.Click
con.Open()
Dim LRN As Integer = TextBoxLRN.Text
Dim FULLNAME As String = TextBoxFullName.Text
Dim GENDER As String = ComboBoxGen.SelectedItem
Dim COURSE As String = TextBoxCourse.Text
Dim SECTION As String = TextBoxSection.Text
query = "UPDATE StudentInfoTbl
SET [FULL NAME] = #FULLNAME, [GENDER] = #GENDER, [COURSE] = #COURSE,
[SECTION] = #SECTION
WHERE [LRN] = #LRN ;" --> 'HERE IS THE ERROR
cmd.Connection = con
cmd.CommandText = query
cmd.Parameters.AddWithValue("#LRN", TextBoxLRN.Text)
cmd.Parameters.AddWithValue("#FULL NAME", TextBoxFullName.Text)
cmd.Parameters.AddWithValue("#GENDER", ComboBoxGen.SelectedItem)
cmd.Parameters.AddWithValue("#COURSE", TextBoxCourse.Text)
cmd.Parameters.AddWithValue("#SECTION", TextBoxSection.Text)
cmd.ExecuteNonQuery()
MessageBox.Show(TextBoxLRN.Text & " Record hass been successfully updated!", "Record Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
ClearTextBox()
BindData()
con.Close()
End Sub
my WHERE clause in SQL query is not being read but when I remove the WHERE clause, all the data from my data table are updated. I want to specify that LRN data will be updated.
Can you guys help me?
Private Sub BtnSimpan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSimpan.Click
If BtnSimpan.Text = "&Simpan" Then
If txtKode.Text = "" Then
MsgBox("Kode Harus Di isi", MsgBoxStyle.Exclamation, "Peringatan")
txtKode.Focus()
Exit Sub
End If
Call bukaDB()
CMD = New MySqlCommand("SELECT KodeBarang from tabelbarang WHERE KodeBarang = '" & txtKode.Text & "'", Conn)
RD = CMD.ExecuteReader()
RD.Read()
If RD.HasRows Then
MsgBox("Maaf, Data dengan Kode tersebut telah ada", MsgBoxStyle.Exclamation, "Peringatan")
Else
simpan = "INSERT INTO tabelbarang (KodeBarang,NamaBarang,HargaBeli,HargaJual,Stok) VALUES ('" & txtKode.Text & "','" & txtNamaBarang.Text & "','" & txtHargaBeli.Text & "','" & txtHargaJual.Text & "','" & txtStok.Text & "')"
CMD = New MySqlCommand(simpan, Conn)
CMD.ExecuteNonQuery()
Call isiGrid()
BtnSimpan.Text = "&Tambah"
Call Bersih()
End If
Else
BtnSimpan.Text = "&Simpan"
'Call Bersih()
txtKode.Enabled = True
txtNamaBarang.Enabled = True
txtHargaBeli.Enabled = True
txtHargaJual.Enabled = True
txtStok.Enabled = True
txtKode.Focus()
End If
End Sub
There were several out-dated practices in the code from the question. The code below is updated for modern coding styles, and the mere act of using modern styles will also solve the issue from the question... that is, if you had followed good coding practices from the beginning, this whole class of issue is solved and you would never have had this problem.
This also fixes the HUGE GAPING SECURITY ISSUE from the original, which again would have been avoided completely just from keeping up with modern coding standards.
Private Sub BtnSimpan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSimpan.Click
If BtnSimpan.Text = "&Simpan" AndAlso String.IsNullOrWhitespace(txtKode.Text) Then
MsgBox("Kode Harus Di isi", MsgBoxStyle.Exclamation, "Peringatan")
txtKode.Focus()
Exit Sub
End If
If BtnSimpan.Text <> "&Simpan" Then
BtnSimpan.Text = "&Simpan"
'Bersih()
txtKode.Enabled = True
txtNamaBarang.Enabled = True
txtHargaBeli.Enabled = True
txtHargaJual.Enabled = True
txtStok.Enabled = True
txtKode.Focus()
Exit Sub
End If
'Do NOT try to re-use the same connection throughout your application!
' It really is more efficient to create a brand new object for most queries,
' and only share the connection string.
'Also, JUST DO THE INSERT.
'Make sure there is a unique constraint on the KodeBarang column,
' and handle the exception if it fails.
' Correct for *either one* of the above issues, and the
' problem in the question never would have happened.
Try
Using CN As New MySqlConnection("Connection string here"), _
CMD As New MySqlCommand("INSERT INTO tabelbarang (KodeBarang,NamaBarang,HargaBeli,HargaJual,Stok) VALUES (#KodeBarang, #NamaBarang, #HargaBeli, #HargaJual, #Stok)", CN)
CMD.Parameters.AddWithValue("#KodeBarang", txtKode.Text)
CMD.Parameters.AddWithValue("#NamaBarang", txtNamaBarang.Text)
CMD.Parameters.AddWithValue("#HargaBeli", txtHargaBeli.Text)
CMD.Parameters.AddWithValue("#HargaJual", txtHargaJual.Text)
CMD.Parameters.AddWithValue("#Stok", txtStok.Text)
CN.Open()
CMD.ExecuteNonQuery()
End Using
isiGrid()
BtnSimpan.Text = "&Tambah"
Catch ex As MySqlException When ex.Code = 1062 '1062 is Duplicate Key Violation
MsgBox("Maaf, Data dengan Kode tersebut telah ada", MsgBoxStyle.Exclamation, "Peringatan")
End Try
End Sub
How can I make this work?
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
conndb = New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
COMMAND = New OleDbCommand(str, conndb)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conndb.Dispose()
End Try
End Sub
I need help on how can I make this run without errors, Im using ms access as my database source. There seems to be an error using this code, this code works perfectly fine with mysql but in ms access, it says data mistype error or something like that. Need your help, thanks
Remove the ' surrounding the field CustomerID in your query :
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
becomes :
str = "Select * FROM customer WHERE CustomerID = " & ListView.FocusedItem.Text
MS Access sees a string when you put an apostrophe, so there is a Type Mismatch Exception, because it is expecting a number...
However, this is a pretty bad idea as Parametrized queries are a better way of doing this (see : Why should I create Parametrized Queries ?)
Also, Use Using
So all in all, it's just another brick in the wall :
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
Using conndb As New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = #Customer"
Using COMMAND As New OleDbCommand(str, conndb)
COMMAND.Parameters.Add("#Customer", SqlDbType.Integer).Value = Integer.Parse(ListView.FocusedItem.Text)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Take a look at this sample code that I put together a while back. You can probably learn a lot from this.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\your_path\Desktop\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
Private Sub txtuser_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtuser.LostFocus
Try
con.Open()
adapter.Fill(table)
sql = "Select * from login "
command = New MySqlCommand(sql, con)
myreader = command.ExecuteReader
Dim a As Integer
Dim b As Integer
a = table.Rows.Count
a -= 1
b = 0
If table.Rows.Count > 0 Then
While (b <= a)
If txtuser.Text = table.Rows(b).Item("username") Then
usercons.Visible = True
PictureBox1.Visible = False
txtuser.Text = ""
btnsave.Enabled = False
ElseIf Not txtuser.Text = table.Rows(b).Item("username") Then
usercons.Visible = False
PictureBox1.Visible = True
btnsave.Enabled = False
End If
b += 1
End While
End If
Catch ex As MySqlException
MsgBox("An Error Occurred. " & ex.Number & " – " & ex.Message)
End Try
con.Close()
End Sub
This is the quick but highly dangerous way of doing it open to all sorts of abuse:
sql = "Select * from login WHERE username='" & txtuser.Text & "'
There is a better way, create a parameter:
con.Open()
adapter.Fill(table)
sql = "Select * from login WHERE username=#username"
command = New MySqlCommand(sql, con)
Dim param As New SqlParameter("#username", SqlDbType.VarChar)
command.Parameters.Add(param)
myreader = command.ExecuteReader
Then check the Rows property, if more than 0 rows, you have selected the user.