search using multiple criteria vb.net - vb.net

Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn.Open()
Dim sql = "SELECT * FROM [maint]"
dt.Clear()
If R1.Checked Then sql = sql & " where datevisite like '%" & dateintervention.Text & "%' "
If R2.Checked Then sql = sql & " [centr] ='" & Me.centra.Text & "'"
If R3.Checked Then sql = sql & "and [Priorité] ='" & Me.Priorite.Text & "'"
If R4.Checked Then sql = sql & "and [Etat_intervention] ='" & Me.etat.Text & "'"
Dim adapter As New OleDbDataAdapter(sql, MyConn)
adapter.Fill(dt)
DGV.DataSource = dt
DGV.Refresh()
MyConn.Close()
End Sub
problem =Syntax error in FROM clause. I want to search using multiple critera using checkbox R1 R2 R3 R4 and the resultat in my datagridview

You need to add a space between your search statements:
If R1.Checked Then sql = sql & " where datevisite like '%" & dateintervention.Text & "%' "
If R2.Checked Then sql = sql & " [centr] ='" & Me.centra.Text & "' "
If R3.Checked Then sql = sql & " and [Priorité] ='" & Me.Priorite.Text & "' "
If R4.Checked Then sql = sql & " and [Etat_intervention] ='" & Me.etat.Text & "' "
Your SQL reads like this: where datevisite like '%%'and [Priorité] =''and
Better Solution:
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn.Open()
Dim sql = "SELECT * FROM [maint] where 1=1 "
dt.Clear()
If R1.Checked Then sql = sql & " and datevisite like '%" & dateintervention.Text & "%' "
If R2.Checked Then sql = sql & " and [centr] ='" & Me.centra.Text & "'"
If R3.Checked Then sql = sql & " and [Priorité] ='" & Me.Priorite.Text & "'"
If R4.Checked Then sql = sql & " and [Etat_intervention] ='" & Me.etat.Text & "'"
Dim adapter As New OleDbDataAdapter(sql, MyConn)
adapter.Fill(dt)
DGV.DataSource = dt
DGV.Refresh()
MyConn.Close()
End Sub
With Parameters:
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim adapter As New OleDbDataAdapter()
Dim command As New OleDbCommand()
Dim sql = "SELECT * FROM [maint] where 1=1 "
Try
MyConn.Open()
dt.Clear()
If R1.Checked Then
sql = sql & " and datevisite like '' "
command.Parameters.AddWithValue("datevisite", "%" & dateintervention.Text & "%")
End If
If R2.Checked Then
sql = sql & " and [centr] = ? "
command.Parameters.AddWithValue("centr", Me.centra.Text)
End If
If R3.Checked Then
sql = sql & " and [Priorité] = ? "
command.Parameters.AddWithValue("Priorité", Me.Priorite.Text)
End If
If R4.Checked Then
sql = sql & " and [Etat_intervention] = ? "
command.Parameters.AddWithValue("Etat_intervention", Me.etat.Text)
End If
command.Connection = MyConn
command.CommandText = sql
adapter.SelectCommand = command
adapter.Fill(dt)
DGV.DataSource = dt
DGV.Refresh()
Catch exp As Exception
Throw exp
Finally
If MyConn IsNot Nothing Then MyConn.Close()
End Try
End Sub

If R1.Checked is false and R2.Checked is true, then you have no WHERE keyword ... your not building the dynamic SQL statement properly.
Also this is highly susceptible to SQL Injection

Related

VB.net - Syntax error in ms access SQL update query

I have prepared my project in vb.net with access database, but I am getting an error like "syntax error in update statement"
I have used following code:
Dim cn As New OleDb.OleDbConnection
Dim cm As New OleDb.OleDbCommand
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\NAV Vikram\DATABASE NAVPREET.mdb"
cn.Open()
cm.Connection = cn
cm.CommandText = "UPDATE DATAENTRY2 set [DIAGNOSIS]='" & TextBox13.Text & "',WHERE[opdno]='" & TextBox1.Text & "' "
cm.ExecuteNonQuery()
Any help would be appreciated.
omit , before WHERE and add space after it. Change:
cm.CommandText = "UPDATE DATAENTRY2 set [DIAGNOSIS]='" & TextBox13.Text & "',WHERE[opdno]='" & TextBox1.Text & "' "
to:
cm.CommandText = "UPDATE DATAENTRY2 set [DIAGNOSIS]='" & TextBox13.Text & "' WHERE [opdno]='" & TextBox1.Text & "' "
Also Use SQL parameters. (Not very keen to vb to show you example)
You have syntax error in your query. Please remove comma (,) you have used before where clause from query, as it is used to separate two different column
Dim cn As New OleDb.OleDbConnection
Dim cm As New OleDb.OleDbCommand
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\NAV Vikram\DATABASE NAVPREET.mdb"
cn.Open()
cm.Connection = cn
cm.CommandText = "UPDATE DATAENTRY2 set [DIAGNOSIS]='" & TextBox13.Text & "' WHERE[opdno]='" & TextBox1.Text & "' "
cm.ExecuteNonQuery()

VB.NET: Cannot display selected data from access database into datagridview

I have been trying to display selected data from Access database into datagridview on pressing the button but its not displaying any records neither it is showing any error.
Dim third_da As OleDb.OleDbDataAdapter
Dim third_ds As New DataSet
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
con.Open()
Dim cb_two As New OleDb.OleDbCommandBuilder(third_da)
query_three = "SELECT emp_timing.emp_code, emp_timing.day, emp_timing.travel_time, emp_timing.travel_dest,emp_timing.emp_timein,emp_timing.emp_timeout, emp_timing.emp_hours, emp_timing.emp_mins " & _
"FROM emp_timing WHERE (((emp_timing.emp_code)=" & empcode & ") AND ((emp_timing.day) Like '??/" & ComboBox1.Text & "/20" & TextBox9.Text & "'))"
' "WHERE (((emp_timing.emp_code)=22) AND ((emp_timing.day) Like '??/05/2016'))"
third_da = New OleDb.OleDbDataAdapter(query_three, con)
third_da.Fill(third_ds, "ets")
DataGridView1.DataSource = third_ds.Tables("ets")
con.Close()
Dim view As New DataView(third_ds.Tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
DataGridView1.ReadOnly = True
DataGridView1.CancelEdit()
End Sub
Thanks in Advance!
You can change you condition of emp_timing.day field in query like this :
(Month(emp_timing.day) = & ComboBox1.Text &
and Year(emp_timing.day) = "20" & TextBox9.Text & " )
But, I advice you to use the Parameter to avoid SQL injections , like this :
query_three = "SELECT emp_timing.emp_code, emp_timing.day, emp_timing.travel_time, emp_timing.travel_dest,emp_timing.emp_timein,emp_timing.emp_timeout, emp_timing.emp_hours, emp_timing.emp_mins " &
"FROM emp_timing WHERE (((emp_timing.emp_code)= #empcode) AND ((emp_timing.day) BETWEEN #startDate AND #endDate ))"
Dim startDate As New DateTime("20" & TextBox9.Text, ComboBox1.Text, 1)
Dim endDate As DateTime = startDate.AddMonths(1).AddDays(-1)
Dim cmd As New OleDbCommand(query_three, con)
cmd.Parameters.AddWithValue("#empcode", empcode)
cmd.Parameters.AddWithValue("#startDate", startDate.ToString("#yyyy/MM/dd#"))
cmd.Parameters.AddWithValue("#endDate", endDate.ToString("#yyyy/MM/dd#"))
third_da = New OleDb.OleDbDataAdapter(cmd)

Syntax error in update query in VB .NET

I'm trying to run a SQL command in VB .NET but it returns a error message of syntax error in my string variable which I just not able to figure out by myself since this is my first experience for programming with SQL command.The specific message is:
Syntax error (missing operator) in query express '= '045617123'.
Where "045617123" is the data stored in one of the data fields
Can someone please help me out from this? Thank You
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "Provider = Microsoft.ACE.OLEDB.12.0;" & "Data Source = C:\Users\JohnnyCheng\Documents\GradeBook.accdb"
Dim conobj As New OleDb.OleDbConnection(constr)
Dim da1 As New OleDb.OleDbDataAdapter()
Dim da2 As New OleDb.OleDbDataAdapter()
Dim sqlstr1 As String = ""
Dim sqlstr2 As String = ""
conobj.Open()
For i As Integer = 0 To vt1.Rows.Count - 1
sqlstr1 = "UPDATE Students SET LastName = '" & vt1.Rows(i)(1) & "', FirstName = '" & vt1.Rows(i)(2) & "', StreetAddress = '" & vt1.Rows(i)(3) & "', City = '" & vt1.Rows(i)(4) & "', State = '" & vt1.Rows(i)(5) & "', ZipCode = '" & vt1.Rows(i)(6) & "' WHERE = '" & vt1.Rows(i)(0) & "'"
da1.UpdateCommand = New OleDb.OleDbCommand(sqlstr1, conobj)
da1.UpdateCommand.ExecuteNonQuery()
Next
'For i As Integer = 0 To vt2.Rows.Count - 1
'sqlstr2 = "UPDATE Grades SET FirstExam = " & vt2.Rows(i)(1) & ", SecondExam = " & vt2.Rows(i)(2) & ", FinalExam = " & vt2.Rows(i)(3) & "WHERE StID = " & vt1.Rows(i)(0)
'da2.UpdateCommand = New OleDb.OleDbCommand(sqlstr2, conobj)
'da2.UpdateCommand.ExecuteNonQuery()
'Next
conobj.Close()
End Sub
Use SqlParameters. If some of your datafields contain ' charachter then sql query return a syntax error. Or users can create a Sql injection query.
Your syntax error in the WHERE = '" & vt1.Rows(i)(0) & "'" There are no column name which must be same as datafield value
Here example of using parameters:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "Provider = Microsoft.ACE.OLEDB.12.0;" & "Data Source = C:\Users\JohnnyCheng\Documents\GradeBook.accdb"
Dim query as New StringBuilder()
With query
.AppendLine("UPDATE Students SET LastName = #LastName")
.AppendLine(", FirstName = #FirstName")
.AppendLine(", StreetAddress = #StreetAddress")
.AppendLine(", City = #City")
.AppendLine(", State = #State")
.AppendLine(", ZipCode = #ZipCode")
.AppendLine("WHERE YourIDField = #ID;")
End With
Using conobj As New OleDb.OleDbConnection(constr)
conobj.Open()
Dim da1 As New OleDb.OleDbDataAdapter()
For i As Integer = 0 To vt1.Rows.Count - 1
Using updCommand As New OleDb.OleDbCommand(query.ToString(), New OleDb.OleDbConnection(""))
updCommand.Parameters.AddWithValue("#LastName", vt1.Rows(i)(1))
updCommand.Parameters.AddWithValue("#FirstName ", vt1.Rows(i)(2))
updCommand.Parameters.AddWithValue("#StreetAddress ", vt1.Rows(i)(3))
updCommand.Parameters.AddWithValue("#City ", vt1.Rows(i)(4))
updCommand.Parameters.AddWithValue("#State ", vt1.Rows(i)(5))
updCommand.Parameters.AddWithValue("#ZipCode", vt1.Rows(i)(6))
updCommand.Parameters.AddWithValue("#ID", vt1.Rows(i)(0))
da1.UpdateCommand = updCommand
da1.UpdateCommand.ExecuteNonQuery()
End Using
Next
End Using
End Sub

VB.NET SQL Server Insert - ExecuteNonQuery: Connection property has not been initialized

In the form load event, I connect to the SQL Server database:
Private Sub AddBook_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myConnection = New SqlConnection("server=.\SQLEXPRESS;uid=sa;pwd=123;database=CIEDC")
myConnection.Open()
End Sub
Here in the Insert event, I use the following code:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")")
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
And It produces the following error:
ExecuteNonQuery: Connection property has not been initialized
Connection Assignment - You aren't setting the connection property of the SQLCommand. You can do this without adding a line of code. This is the cause of your error.
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")", MyConnection)
Connection Handling - You also need to remove `MyConnection.Open' from your Load Handler. Just open it and close it in your Click Handler, as you are currently doing. This is not causing the error.
Parameterized SQL - You need to utilize SQL Parameters, despite the fact that you are not using a Stored Procedure. This is not the cause of your error. As Conrad reminded me, your original code dumps values straight from the user into a SQL Statement. Malicious users will steal your data unless you use SQL Parameters.
Dim CMD As New SqlCommand("Select * from MyTable where BookID = #BookID")
CMD.Parameters.Add("#BookID", SqlDbType.Int).Value = CInt(TXT_BookdID.Text)
You need to set the Connection property on the command:
myCommand.Connection = myConnection
Pretty much what the error message implies - the Connection property of the SqlCommand object hasn't been assigned to the connection you opened (in this case you called it myConnection).
Also, a word of advice here. Do some reading on sql parameters - doing sql concatenation from user input without any sanity checks is the way SQL injection attacks happen.
This is one way to do it:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand( _
"INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, " & _
" EnterDate, CatID, RackID, Amount) " & _
"VALUES(#bookCode, #bookTitle, #author, #publishingYear, #price, #enterDate, " & _
" #catId, #rackId, #amount)")
myCommand.Connection = myConnection
with myCommand.Parameters
.AddWithValue("bookCode", txtBookCode.Text)
.AddWithValue("bookTitle", txtTitle.Text)
.AddWithValue("author", txtAuthor.Text)
.AddWithValue("publishingYear", txtPublishYear.Text)
.AddWithValue("price", txtPrice.Text)
.AddWithValue("enterDate", txtEnterDate.Text)
.AddWithValue("catId", txtCategory.Text)
.AddWithValue("rackId", txtRack.Text)
.AddWithValue("amount", txtAmount.Text)
end with
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
Module Module1
Public con As System.Data.SqlClient.SqlConnection
Public com As System.Data.SqlClient.SqlCommand
Public ds As System.Data.SqlClient.SqlDataReader
Dim sqlstr As String
Public Sub main()
con = New SqlConnection("Data Source=.....;Initial Catalog=.....;Integrated Security=True;")
con.Open()
frmopen.Show()
'sqlstr = "select * from name1"
'com = New SqlCommand(sqlstr, con)
Try
com.ExecuteNonQuery()
'MsgBox("success", MsgBoxStyle.Information)
Catch ex As Exception
MsgBox(ex.Message())
End Try
'con.Close()
'MsgBox("ok", MsgBoxStyle.Information, )
End Sub
End Module
Please try to wrap the use of your connections (including just opening) inside a USING block. Assuming the use of web.config for connection strings:
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("web.config_connectionstring").ConnectionString)
Dim query As New String = "select * from Table1"
Dim command as New SqlCommand(query, connection)
Using connection
connection.Open()
command.ExecuteNonQuery()
End Using
And PARAMETERIZE anything user-entered.. please!

Data Reader formatting output

I'm using the following function to generate a list of users connected to a selected database. How would I change this to a single line for multiple identical results?
For example: "sa (3) - MYCOMPUTER" rather than listing "sa - MYCOMPUTER" three times?
Function ConnectedUsers(ByVal SelectedDatabase As String, ByVal SelectedInstance As String)
Dim myCommand As SqlCommand
Dim dr As SqlDataReader
Dim mystring As String = String.Empty
Try
Dim myConn As New SqlConnection(ConnectionString)
myConn.Open()
myCommand = New SqlCommand("select loginame,hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & ";", myConn)
dr = myCommand.ExecuteReader()
While dr.Read()
mystring += GetFullName(dr(0).ToString().Trim()) & " - " & dr(1).Trim() & vbCrLf
End While
dr.Close()
myConn.Close()
Catch e As Exception
MessageBox.Show(e.Message)
End Try
Return mystring
End Function
Thanks.
The SQL Command should be
select loginame, count(*) as Nbr, hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & "' group by loginame;"
and you should change the display to show the count (Nbr in this example) to be something like:
mystring += GetFullName(dr(0).ToString().Trim()) & "(" & dr(1).Trim() & ") - " & dr(2).Trim() & vbCrLf