Search function using combo box,text box and list view - database

i have a few error. i have a search function from the database. when i run the project, and click the SEARCH button to view in the listview, the popup message out called "Incorrect syntax near "CONCAT". here the code for CONCAT
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE CONCAT ('%', #valueName, '%')"
here full code for SEARCH function
Private Sub Search()
ListViewRoom.Items.Clear()
Dim item As New ListViewItem
Dim _isFound As Boolean = False
Dim colName() As String = {"Room_Code", "Room_Type", "Room_No", "Room_Price", "Room_Status", "No_of_Occupancy"}
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE CONCAT ('%', #valueName, '%')"
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Using con As New SqlClient.SqlConnection("Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True")
Using com As New SqlClient.SqlCommand()
With com
.Connection = con
.CommandType = CommandType.Text
.CommandText = strSqlSearch
.Parameters.AddWithValue("#valueName", txtSearch.Text)
End With
Try
con.Open()
Dim dr As SqlClient.SqlDataReader = com.ExecuteReader
While dr.Read
_isFound = True
item = ListViewRoom.Items.Add(dr("Room_Code").ToString)
item.SubItems.Add(dr("Room_Type".ToString))
item.SubItems.Add(dr("Room_No".ToString))
item.SubItems.Add(dr("Room_Price".ToString))
item.SubItems.Add(dr("Room_Status".ToString))
item.SubItems.Add(dr("No_of_Occupancy".ToString))
End While
If Not _isFound Then
MsgBox("No results found.", MsgBoxStyle.OkOnly, "Information")
End If
Catch ex As Exception
MsgBox(ex.Message.ToString(), MsgBoxStyle.OkOnly, "Error")
End Try
End Using
End Using
End Sub
I hope u can help me. Tq

You don't need to use the CONCAT. just remove it from the SQL and it should work.
EDIT
Try this:
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE '%'+ #valueName +'%'"
Edit #2
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE '%" & txtSearch.Text & "%'"
And remove the parameter form the SqlCommand.

Related

Join Excel-Table with SQL Server

My excel-sheet is connected with the data of the sql-server. My clients shall be able to write some columns back to the sql server. The excel-filenames are variable, but the sheeetname and the columns are always static. I tried it with a button and vba but it ends up in error:
Syntaxerror (missing operator) in queryexpression 'UPDATE hbs SET lieferinfo_prio_neu = xlsx.liefer_prio_neu FROM [Provider=SQLOLEDB;Data Source=myserver;Database=mydb;UID=myuser;PWD=mypass;].[tbl_haka_base_size] hbs JOIN [Tabelle3$] xlsx ON xlsx.Artikelnummer'
The internal excel-sheetname is 'Tabelle3', the custom-name is 'Hakabase':
I tried both names without any result.
My code:
Dim excelConn As String
Dim sqlServerConn As String
Dim sqlCommand As String
Dim conn As ADODB.Connection
excelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
& ThisWorkbook.FullName _
& ";Extended Properties=""Excel 12.0 Xml;HDR=Yes;IMEX=1"";"
sqlServerConn = "[Provider=SQLOLEDB;" _
& "Data Source=myserver;" _
& "Database=mydb;" _
& "UID=ymuser;PWD=mypass;]"
sqlCommand = "UPDATE hbs " _
& " SET lieferinfo_prio_neu = xlsx.liefer_prio_neu " _
& " FROM " & sqlServerConn & ".[tbl_haka_base_size] hbs " _
& " JOIN [Tabelle3$] xlsx " _
& " ON xlsx.Artikelnummer=hbs.artikelnummer"
Set conn = New ADODB.Connection
conn.Open excelConn
conn.Execute sqlCommand
I've also tried to connect to the sqlserver + join the excel-data via openrowset but the server disallowed that:
& " JOIN OPENROWSET('MSDASQL', " _
& " 'Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" _
& ThisWorkbook.FullName & "', 'SELECT * FROM [Tabelle3$]') xlsx" _
Installable ISAM not found
I think I have to create a linked server for each file and enable 'InProcess' for those files. This is not possible because the files are variable.
I've found an alternative solution which is a little bit slow so I still hope someone else is able to answer my question.
The alternative solution is to iterate through each row.. The file got about 150.000 rows and just for 10.000 rows I am waiting about 10 minutes..
Here is the part of iterating
For Each range In sheet.rows: Do
'Continue on headline
If range.Row = 1 Or range.EntireRow.Hidden = True Then
Exit Do
End If
If Len(sheet.Cells(range.Row, lieferInfoColumnIndex)) > 0 Then
articleNumber = sheet.Cells(range.Row, artNoColumnIndex)
UpdateDatabase (articleNumber)
savings = savings + 1
End If
Loop While False: Next range
Here is the slow update function for each row:
Private Sub UpdateDatabase(articleNumber As String)
Dim sqlServerConn As String
Dim sqlCommand As String
Dim conn As ADODB.Connection
sqlServerConn = "Provider=SQLOLEDB;" _
& "Data Source=myserver;" _
& "Database=mydb;" _
& "UID=myuser;PWD=mypass;"
sqlCommand = "UPDATE hbs " _
& "SET lieferinfo_prio_neu=NULL " _
& "FROM [TBL_HAKA_BASE] hbs " _
& "WHERE Artikelnummer=" + articleNumber
Set conn = New ADODB.Connection
conn.Open sqlServerConn
conn.Execute sqlCommand
End Sub

update button codes for VB.net with sql-server

I have create a library management system. here if I want to update a book's particular record its updating all the records in the SQL-server database. how can I write code for update a particular record only. here is my code,
Private Sub btnedit_Click(sender As Object, e As EventArgs) Handles btnedit.Click
con.ConnectionString = "data source=hp-pc\sqlexpress; initial catalog=Library_DB;integrated security= true"
con.Open()
Dim comd As New SqlCommand("update Book set Book_Id='" & TextBox1.Text & "',Bk_Name='" & TextBox2.Text & "',Author_Name='" & TextBox3.Text & "', Year_of_release='" & TextBox4.Text & "',Availability_of_bks='" & TextBox5.Text & "'", con)
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Add a WHERE clause in your SQL command to specify which book will be updated..
use the ID number of the book you want to update.
and avoid concatenating in your sql command, use parameter #
Dim comd As New SqlCommand("update Book set Book_Id=#bookID, Bk_Name=#bkName, Author_Name=#author, Year_of_release=#release, Availability_of_bks=#avail WHERE Book_Id=#whereID", con)
comd.Parameters.Add("#bookID", SqlDbType.String).Value = TextBox1.Text
comd.Parameters.Add("#bkName", SqlDbType.String).Value = TextBox2.Text
comd.Parameters.Add("#author", SqlDbType.String).Value = TextBox3.Text
comd.Parameters.Add("#release", SqlDbType.String).Value = TextBox4.Text
comd.Parameters.Add("#avail", SqlDbType.String).Value = TextBox5.Text
comd.Parameters.Add("#whereID", SqlDbType.String).Value = "Book ID HERE"
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
You need to add a WHERE clause to your SqlCommand so that SQL Server knows what record to update. Without a WHERE clause, it will update the entire table. See below:
con.ConnectionString = "data source=hp-pc\sqlexpress; initial catalog=Library_DB;integrated security= true"
con.Open()
Dim comd As New SqlCommand("update Book set Book_Id='" & TextBox1.Text & "',Bk_Name='" & TextBox2.Text & "',Author_Name='" & TextBox3.Text & "', Year_of_release='" & TextBox4.Text & "',Availability_of_bks='" & TextBox5.Text & "' WHERE Book_Id='{**Put your book id here**}'", con)
comd.ExecuteNonQuery()
MessageBox.Show("Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

IF adding record is cancelled then return adding another record

Im having a problem of adding records when I click the messagebox and i answered is no then cancel it and add another record but im having a message of connection has not been initialized heres my code thank you.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim reader As SqlDataReader
conn.Open()
Dim bday As String
bday = adyear.Text & "-" & admonth.Text & "-" & adday.Text
If adfirstname.Text.Length < 2 Then
MessageBox.Show("Firstname is too short")
End If
Dim exist As String
exist = "select * from record where firstname='" & adfirstname.Text & "'" & " and lastname='" & adlastname.Text & "';"
cmd = New SqlCommand(exist, conn)
reader = cmd.ExecuteReader
If reader.HasRows = True Then
If MsgBox("THE MEMBER YOU ARE TRYING TO ADD HAS AN SAME FIRSTNAME AND LASTNAME IN THE RECORD DO YOU WISH TO CONTINUE ?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
ElseIf adage.Text < 18 Then
If MsgBox("The member is less than 18 years old is this an intern?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Dim add As String
add = "insert into record(firstname,middlename,lastname,birthday,age,jobposition)" & _
"values(" & _
"'" & adfirstname.Text & "'," & _
"'" & admiddlename.Text & "'," & _
"'" & adlastname.Text & "'," & _
"'" & bday & "'," & _
"'" & adage.Text & "'," & _
"'" & adjobposition.Text & "');"
cmd = New SqlCommand(add, conn)
cmd.ExecuteNonQuery()
MessageBox.Show("Added Complete")
Else
MsgBox("Action is Terminated")
' code for return to adding and stop the messagebox of the connection has not been initialized
End If
End If
End If
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
End Class
Well, since it appears the conn is a form level object you would need to call
conn = New SqlConnection(<connection string>)
before you can use it to open the connection. Given that you call
conn.Dispose()
to destroy the conn instance in the Finally block it appears that you do not keep an open connection around for long.

Incorrect syntax near 'AvayaSBCCRT'

I'm really sorry to be asking and I'm sure it's extremely simple to answer but whenever I try to run the macro in excel below, I get the error message stated in the title:
Sub CallsMacro()
Dim ConData As ADODB.Connection
Dim rstData As ADODB.Recordset
Dim wsSheet As Worksheet
Dim strServer As String
Dim strDatabase As String
Dim strFrom As String
Dim strto As String
Dim intCount As Integer
Set wsSheet = ActiveWorkbook.Worksheets("Refresh")
With wsSheet
strServer = "TNS-CCR-02"
strDatabase = "AvayaSBCCRT"
strFrom = .Range("C$2")
strto = .Range("C$3")
End With
Set ConData = New ADODB.Connection
With ConData
.ConnectionString = "Provider=SQLOLEDB;Data Source=" & strServer & ";" & "Initial Catalog=" & ";" & "persist security info=true;" & "User Id=dashboard; Password=D4$hboard;"
.CommandTimeout = 1800
.Open
End With
''Create the recordset from the SQL query
Set rstData = New ADODB.Recordset
Set wsSheet = ActiveWorkbook.Worksheets("Calls")
With rstData
.ActiveConnection = ConData
.Source = "SELECT DISTINCT CAST(c.createdate AS date) as [Date]," & _
"CASE WHEN c.[CategoryID] = 1 then 'Outbound' WHEN c.[CategoryID] = 2 then 'Inbound' Else 'Internal' end as [Direction], c.cli as [Number], c.ddi, 'CallCentre' as [Queue], '' as [Queue Time], u.username as [Agent], cast((c.DestroyDate - c.CreateDate) as TIME) as [Duration], 'Connected' as [Status], c.callID as [Reference]" & _
"FROM [AvayaSBCCRT].[dbo].[tblAgentActivity] as a" & _
"JOIN [AvayaSBCCRT].[dbo].[tblCallList] as c on c.calllistid = a.calllistid" & _
"JOIN [AvayaSBCCRT].[dbo].[tblUsers] as u on u.userid = a.AgentID" & _
"WHERE c.createdate between '" & strFrom & "' and '" & strto & "'" & _
"AND a.[ActivityID] = 3 "
.CursorType = adOpenForwardOnly
.Open
End With
wsSheet.Activate
Dim Lastrow As Long
Lastrow = Range("A" & Rows.Count).end(xlUp).Row
Range("A2:J" & Lastrow).ClearContents
If rs.EOF = False Then wsSheet.Cells(2, 1).CopyFromRecordset rsData
rs.Close
Set rs = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
End Sub
I've looked high and low and cannot find the reason for it. Anybody have any ideas?
You're missing spaces from the end of the lines. Your SQL contains for example:
[tblAgentActivity] as aJOIN [AvayaSBCCRT].[dbo].[tblCallList]

Search function using listview in vb

i get a change of data in a first column in a listview after search a data.
Example:
in a first column, the data must display a room code like "3234" but after do a searching the data change to "Room_Code".
Below is the code for search function
Private Sub Search()
ListViewRoom.Items.Clear()
Dim item As New ListViewItem
Dim _isFound As Boolean = False
Dim colName() As String = {"Room_Code", "Room_Type", "Room_No", "Room_Price", "Room_Status", "No_of_Occupancy"}
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy " & _
"FROM Room " & _
"WHERE " & colName(cboSearch.SelectedIndex) & " LIKE '%" & txtSearch.Text & "%'"
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Using con As New SqlClient.SqlConnection("Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True")
Using com As New SqlClient.SqlCommand()
With com
.Connection = con
.CommandType = CommandType.Text
.CommandText = strSqlSearch
End With
Try
con.Open()
Dim dr As SqlClient.SqlDataReader = com.ExecuteReader
While dr.Read
_isFound = True
item = ListViewRoom.Items.Add("Room_Code".ToString)
item.SubItems.Add(dr("Room_Type".ToString))
item.SubItems.Add(dr("Room_No".ToString))
item.SubItems.Add(dr("Room_Price".ToString))
item.SubItems.Add(dr("Room_Status".ToString))
item.SubItems.Add(dr("No_of_Occupancy".ToString))
End While
If Not _isFound Then
MsgBox("No results found.", MsgBoxStyle.OkOnly, "Information")
End If
Catch ex As Exception
MsgBox(ex.Message.ToString(), MsgBoxStyle.OkOnly, "Error")
End Try
End Using
End Using
Tq
Um, because you're telling it to:
item = ListViewRoom.Items.Add("Room_Code".ToString)
I suppose that that should be:
item = ListViewRoom.Items.Add(dr("Room_Code").ToString)
By the way, you've got several other pointless calls to ToString too, e.g.
item.SubItems.Add(dr("Room_Type".ToString))
What's the point of calling ToString on a literal? Surely it's the field value that you want converted to a String:
item.SubItems.Add(dr("Room_Type").ToString())
You really should be using a DataGridView and simply binding a DataTable instead of abusing a ListView, which is NOT a grid control.

Resources