da.fill incorrect syntax near ')' - vb.net

I'm having a problem from the line
da.Fill(ds, "Employee")
and I don't have any clue to solve this. Can anyone help?
This is my actual code:
Private Sub btnsearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsearch.Click
Dim da As New SqlClient.SqlDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
If txtssn.Text = "" Then
MsgBox("Please input SSN.", MsgBoxStyle.Exclamation, "Company Records - Employee")
Else
con.Open()
Dim cmd As New SqlCommand("SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "')", con)
da.SelectCommand = cmd
da.Fill(ds, "Employee")
dt = ds.Tables("Employee")
If (dt.Rows.Count > 0) Then
Me.txtfname.Text = dt.Rows(0).Item(1)
Me.txtmi.Text = dt.Rows(0).Item(2)
Me.txtlname.Text = dt.Rows(0).Item(3)
Me.dtpbdate.Text = dt.Rows(0).Item(5)
Me.txtaddress.Text = dt.Rows(0).Item(6)
Me.cmbsex.Text = dt.Rows(0).Item(7)
Me.txtsalary.Text = dt.Rows(0).Item(8)
Me.cmbsuperssn.Text = dt.Rows(0).Item(9)
'Me.cmbdept.Text =
btnedit.Enabled = True
btndelete.Enabled = True
editable()
Else
MsgBox("Record Not Found", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Company Records - Employee")
End If
con.Close()
End If

Remove the closing parantheses since that's a SELECT not an INSERT:
"SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "'"
However, i would always use sql-parameters to prevent sql-injection.
Using con As New SqlConnection("ConenctionString")
Using da As New SqlDataAdapter("SELECT * FROM [Employee] WHERE [Ssn] = #SSN", con)
da.SelectCommand.Parameters.Add("#SSN", SqlDbType.VarChar).Value = txtssn.Text
da.Fill(ds, "Employee")
End Using
End Using

Remove the trailing ) from your SQL statement.
"SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "'"
Also see why you shouldn't be doing it in the first place.

Their is syntax error near your SQLstatement so you need to remove an unwanted ( to make this statement workable.
Dim cmd As New SqlCommand("SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "'", con)

Related

VB.net and DATABASE. i Kept getting an record without an Entry Level record (IN)

i kept getting an record without an Entry Level record (IN) that supposably will have an IN(database record) instead of NOTHING... However after it was scanned after another try only when IN is found in the database.... Overall I will just make an details but empty entry_record which is incomplete
enter image description here
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()
End While
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
If (dr("entry_record")) = "IN" Then
record = "OUT"
ElseIf (dr("entry_record")) = "OUT" Then
record = "IN"
ElseIf (dr("entry_record")) = String.Empty Then
record = "IN"
End If
status.Text = (record)
End While
dr.Close()
cn.Close()
ConnectToDB()
sql = "insert into monitoring (id_num, fname, lname, status, entry_record, floor_level, date) VALUES (#num, #name, #lname, #stat, #record, #lev,#date)"
cmd = New MySqlCommand(sql, cn)
With cmd
.Parameters.AddWithValue("#num", idnum)
.Parameters.AddWithValue("#name", TextBox2.Text)
.Parameters.AddWithValue("#lname", TextBox6.Text)
.Parameters.AddWithValue("#stat", TextBox5.Text)
.Parameters.AddWithValue("#lev", levellock.sharevalue)
.Parameters.AddWithValue("#record", status.Text)
.Parameters.AddWithValue("#date", Date.Now)
.ExecuteReader()
End With
MsgBox("Details has been saved!", vbInformation, "Saved")
cmd = Nothing
dr.Close()
cn.Close()
End If
End Sub
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()
status.Text = "IN"
End While
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
'If status.Text = "IN" Then
'record = "OUT"
' ElseIf status.Text = "OUT" Then
' record = "IN"
' ElseIf status.Text = String.Empty Then
' record = "IN"
' End If
'status.Text = (record)
If (dr("entry_record")) = "IN" Then
record = "OUT"
ElseIf (dr("entry_record")) = "OUT" Then
record = "IN"
ElseIf (dr("entry_record")) = String.Empty Then
record = "IN"
End If
status.Text = (record)
End While
dr.Close()
cn.Close()
stated the STATUS as IN

Use VB.NET Manipulate Microsoft Access Database

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

show multiple data on rcihtextbox from database column error

What's wrong with my code? the error happens on UPDATE block "
If reader1.Read() Then
rtbURThirdMolar.Text = reader1.Item("Up_Right_3rd_Molar")" Conversion from type 'DBNull' to type 'String' is not valid
Private Sub txtURThirdMolar_KeyDown(sender As Object, e As KeyEventArgs) Handles txtURThirdMolar.KeyDown
MySqlConn.open()
If e.KeyCode = Keys.Enter Then
query1 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
reader = cmd1.ExecuteReader
If reader.HasRows Then
Dim i As Integer
With cmd
.Connection = MySqlConn
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar = concat('" & txtURThirdMolar.Text & Environment.NewLine & "',Up_Right_3rd_Molar) WHERE Patient_ID_Number = " & lblID.Text
reader.Close()
i = .ExecuteNonQuery
End With
If i > 0 Then
MsgBox("Updated!", MsgBoxStyle.Information, "Success")
txtURThirdMolar.Text = ""
Dim query2 As String
Dim reader1 As MySqlDataReader
Dim cmd2 As MySqlCommand
query2 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd2 = New MySqlCommand(query2, MySqlConn)
reader1 = cmd2.ExecuteReader
If reader1.Read() Then
rtbURThirdMolar.Text = reader1.Item("Up_Right_3rd_Molar") 'THIS IS WHERE THE ERROR OCCURS
End If
Else
MsgBox("Failed", MsgBoxStyle.Information, "Failed")
End If
Else
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO teethhistory (Patient_ID_Number, Fullname, Up_Right_3rd_Molar )" &
"VALUES ('{0}' ,'{1}' ,'{2}')",
lblID.Text,
lblFullname.Text,
txtURThirdMolar.Text)
reader.Close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Saved!", MsgBoxStyle.Information, "Success")
txtURThirdMolar.Text = ""
Dim query2 As String
Dim reader2 As MySqlDataReader
Dim cmd2 As MySqlCommand
query2 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd2 = New MySqlCommand(query2, MySqlConn)
reader2 = cmd2.ExecuteReader
If reader2.Read() Then
rtbURThirdMolar.Text = reader2.Item("Up_Right_3rd_Molar")
End If
Else
MsgBox("Saving failed.", MsgBoxStyle.Critical, "Failed")
End If
End If
End If
MySqlConn.close()
End Sub
use
rtbURThirdMolar.Text = reader1.Item("Up_Right_3rd_Molar").ToString
this is because the item you are referencing is NULL.

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

Child list for field salesreport cannot be created

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOk.Click
Dim scan As String = "select ProductCode from products where ProductCode = '" & TextBox1.Text & "';"
connection.Open()
Dim cmd = New MySqlCommand(scan, connection)
Dim dr As MySqlDataReader = cmd.ExecuteReader
If dr.Read = True Then
MsgBox("Match found")
connection.Close()
Dim insert As String = "insert into salesreport (ProductName,ProductPrice) select products.ProductName,products.ProductPrice from products where products.ProductCode = '" & TextBox1.Text & "';"
connection.Open()
da = New MySqlDataAdapter(insert, connection)
da.Fill(ds, "salesreport")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "salesreport"
connection.Close()
Else
connection.Close()
MsgBox("No match found")
TextBox1.Text = ""
TextBox1.Select()
End If
End Sub
INSERT statements doesn't return records.
There is no sense in this situation to use a DataAdapter to INSERT a record.
Use the MySqlCommand.ExecuteNonQuery method to insert your record, then read the added row with a MySqlDataAdapter
Also, do not concatenate text, typed by your user, to build and use an sql text for the database engine. Your code could be easily used to create Sql Injection Attacks.
Dim scan As String = "select ProductCode from products " +
"where ProductCode = ?prodCode"
connection.Open()
Dim cmd = New MySqlCommand(scan, connection)
cmd.Parameters.AddWithValue("?prodCode", TextBox1.Text)
..........
Dim insert As String = "insert into salesreport (ProductName,ProductPrice) " +
"select products.ProductName,products.ProductPrice from products " +
"where products.ProductCode = ?prodCode"
cmd = new MySqlCommand(insert, connection)
cmd.Parameters.AddWithValue("?prodCode", TextBox1.Text)
cmd.ExecuteNonQuery()
da = New MySqlDataAdapter(scan, connection)
da.SelectCommand.Parameters.AddWithValue("?prodCode", TextBox1.Text)
da.Fill(ds, "salesreport")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "salesreport"