VB.Net Parameterized LIKE query - vb.net

I am writing a code that will filter account numbers with the format zone-rate-customer_number. An example of that is 125-12-35, where 125 is the zone, 12 is the rate and 35 is the customer number. In my search textbox, I want to enter the zone and the customer number, this will exclude the rate. Here is my code
Dim search As String = txtsearch.Text
Dim sql As String = "SELECT * FROM tblCustomer WHERE [account no] LIKE '%' + #search + '%'"
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = Con
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.Parameters.AddWithValue("[account no]", search)
How can I be able to search in my table using only the zone and customer number?

First, you should collect the "zone" and "customer_number" separately (e.g., in separate text boxes). Then you can do a LIKE search using
' test data
Dim zone As String = "125"
Dim customer_number As String = "35"
Using cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText =
"SELECT * FROM tblCustomer WHERE [account no] LIKE ?"
cmd.Parameters.AddWithValue("?", zone & "-%-" & customer_number)
Using rdr As OleDbDataReader = cmd.ExecuteReader
Do While rdr.Read
Console.WriteLine(rdr("account no"))
Loop
End Using
End Using

Related

I am trying to make search button in vb.net from NTable with Id,Name,Age.I get error on sda.fill(dt) (error:) any help would be appreciated

Private Function search1() As DataTable
Dim query1 As String = "select Id,Name,Age from NTable"
query1 &= "WHERE Id Like '%' +#parm1+ '%' "
query1 &= "OR Name Like '%' +#parm1+ '%' "
query1 &= "OR Age Like '%' +#parm1+ '%' "
query1 &= "OR #parm1=''"
Dim con1 As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Acer Nitro 5\Documents\check.mdf;Integrated Security=True;Connect Timeout=30"
Using conn As SqlConnection = New SqlConnection(con1)
Using cmd As SqlCommand = New SqlCommand(query1, conn)
cmd.Parameters.AddWithValue("#parm1", TextBox1.Text.Trim())
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
error: https://i.stack.imgur.com/hSut2.png
Why Am I getting error in sda.fill(dt)
Below shows how to use a parameter with LIKE when performing a query to a SQL Server database.
Note: In the code below change the table name to your table name.
Public Function GetData(searchStr As String) As DataTable
Dim dt As DataTable = New DataTable()
Dim query As String = "SELECT Id, Name, Age from Employee where Id LIKE #search OR Name like #search OR Age LIKE #search"
Debug.WriteLine(query)
Using con As SqlConnection = New SqlConnection(connectionStr)
'open
con.Open()
Using cmd As SqlCommand = New SqlCommand(query, con)
cmd.Parameters.Add("#search", SqlDbType.VarChar).Value = $"%{searchStr}%"
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim numRowsAffected As Integer = da.Fill(dt)
Debug.WriteLine($"numRows: {numRowsAffected}")
End Using
End Using
End Using
Return dt
End Function
While the above code has been tested and seems to work, I recommend
re-writing your code so that the correct data types are being passed. If the database data type is an integer, then specify SqlDbType.Int and pass an Integer value.
Here's the table definition:
Create table Employee(Id int Identity (1,1),
Name varchar(75),
Age int,
CONSTRAINT PK_Test_Id Primary Key(Id))
Resources:
Interpolated Strings (Visual Basic Reference)

Use sql table like sql parameter in vb.net

I have query with sql parameters. My parameter must be my table from database and I don't now how I can realize this.
I did it so:
myCommand = myConnection.CreateCommand()
myCommand.CommandType = CommandType.Text
myCommand.CommandText =
"SELECT Id, Bez, Param5, Info from Table" & "#idFixed"
myCommand.Parameters.Add("#idFixed", SqlDbType.VarChar).Value = strIdFixed
strIdFixed(transmitted parameter) must be something id, because I have many tables with names Table01, Table02, Table333 ....
I have it
Dim tableName As String = "Test" + strIdFixed.ToString.Trim
Dim builder = New SqlCommandBuilder()
Dim escapedTableName As String = builder.QuoteIdentifier(tableName)
myCommand = myConnection.CreateCommand()
myCommand.CommandType = CommandType.Text
myCommand.CommandText =
"SELECT Id, Bez, Param5, Info from " + escapedTableName
Thank https://stackoverflow.com/a/17948039/6787667

Dynamically retrieve Oracle data from double parameter?

I have names and surnames to retrieve from DB, but It's not working as It should. I get names and surnames from a table where they are in separated columns. Names/surnames are displayed in combobox/textbox combination on my form. Now I need to retrieve this data, but there are only 4 fields in my DB to search, because all names/surnames are combined together in those fields (user request). My code works for 2 searches at a time, but not for all 4. Here is my code:
EDIT (this works now - I've separated parameters and added bracket in OR statements):
Using con As New OracleConnection("Data Source=myDB;User Id=Lucky;Password=MyPassword;")
con.Open()
Using cmd As New OracleCommand()
Dim SQL As String = "Select * FROM MyTable "
Dim conca As String = " Where "
Dim Person1 As String
Person1 = CmbName.Text.Trim & " " & TxtSurname.Text.Trim
If Not CmbName.Text = "" Then
SQL = String.Concat(SQL, conca, " (USER1 = :user OR USER2 = :user1)")
cmd.Parameters.Add(New OracleParameter("user", Person1))
cmd.Parameters.Add(New OracleParameter("user1", Person1))
conca = " and "
End If
Dim Person2 As String
Person2 = CmbName1.Text.Trim & " " & TxtSurname1.Text.Trim
If Not CmbName1.Text = "" Then
SQL = String.Concat(SQL, conca, " (ADMINISTRATOR1 = :admin OR ADMINISTRATOR2 = :admin1)")
cmd.Parameters.Add(New OracleParameter("admin", Person2))
cmd.Parameters.Add(New OracleParameter("admin1", Person2))
conca = " and "
End If
'Retrieve data using execute reader
cmd.Connection = con
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Using
I tried using brackets between "and" & "or", but this still doesn't work. Any suggestions ?
Although I don't like your approach, you should separate the queries or have one function retrieving results for you for each "Person" request. For your solution try to remove this: conca = " and " from the first and second 'if/else' statement. Add each result into your datatable and then load the gridview with the datatable.
You should call a function similar to this to get the results in a data reader and then feed your datatable. This way you can separate your queries. The tricky part is to have an elegant way to load your datagridview. My suggestion is to stop using datatables (they are very bad). You should use IEnumerable or List (Of Object) where you could add the results from each query.
Public Shared Function GetMeDatareader(yourQuery As String) As OracleDataReader
Using con As New OracleConnection("Data Source=myDB;User Id=Lucky;Password=MyPassword;")
con.Open()
Using cmd As New OracleCommand()
Dim SQL As String = yourQuery
'Retrieve data using execute reader
cmd.Connection = con
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Return dr
End Using
End Using
End Function

I can not read from database Visual basic

Dim conStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\databaseVB\bakery.accdb"
Dim conn As New OleDbConnection(conStr)
Dim cmd As New OleDbCommand
Dim reader As OleDbDataReader
Dim Item(5) As String
Dim key = TextBox1.Text
conn.Open()
cmd.Connection = conn
1>>>>> 'cmd.CommandText = "SELECT * FROM Member WHERE number = 3"
2>>>>> cmd.CommandText = "SELECT * FROM Member WHERE number = '" & key & "'"
MessageBox.Show(cmd.CommandText)
reader = cmd.ExecuteReader()
While reader.Read
Item(0) = reader("Number").ToString
Item(1) = reader("FirstName").ToString
Item(2) = reader("LastName").ToString
Item(3) = reader("User").ToString
Item(4) = reader("Pass").ToString
End While
MessageBox.Show(Item(1).ToString)
conn.Close()
from 1>>> I can read Item in databaes
from 2>>> I can not read Item
Try using a parameterized query string:
cmd.CommandText = "SELECT * FROM Member WHERE number = #Number"
After this add your parameters.
//cmd.Parameters.Add("#Number", SqlDbType.Int).Value = 3;
//It is better to use .TryParse(), incase your users write non numerical values in the Textbox
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = (int)TextBox1.Text;
Additionally you need to watch your data types. 3 is of type int, but TextBox1.Text is of type string. You need to parse the string to int in order for it to work.
This should do the trick and prevent ugly syntax juggling, while mixing strings and variables; And prevent you from SQL Injection attacks.

Error in getting Dates in database (BETWEEN Clause| VB.NET|OLE)

before a little time , I used a code to get the dates between 2 dates from the database (column with dates dd/mm/yy) , I think it works nice first time , the code is :
Dim b As New Date
Dim a As Integer
a = Val(tx2.Text)
b = System.DateTime.Today
b = b.AddDays(-a)
MsgBox(b)
Conn.Open()
SQLstr = " Select * from tb where lastvstart BETWEEN #01/01/1800# AND #" & b & "#"
Dim DataAdapter1 As New OleDbDataAdapter(SQLstr, Conn)
DataSet1.Clear()
DataAdapter1.Fill(DataSet1, "Tb")
Conn.Close()
as you see , the code let the user to insert a number and minus it form the date of today , then calculates the date that I want , after that I use BETWEEN Clause to get all dates between them
But now , this code gets some data and overpasses others , I mean some of the dates is between the tow dates but the code never get it , why that happens ?
If you look at the generated SQL string, does it contain the date that you expect? I would assume that the database requires it to follow a specific format (either dd/MM/yyyy or MM/dd/yyyy given the hard coded date in the query). Could it be that your day and month switch places when the string version of the date is created and inserted into your SQL query?
As a side note, I would strongly recommend against concatenating SQL queries together like that. If possible, use parameterized queries instead. That could possibly also remove some type conversion issues.
Update
Here is an example of using a parameterized query over OLE DB to an Access database:
Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""C:\path\file.mdb""")
Using cmd As New OleDbCommand("select * from tb where lastvstart BETWEEN ? AND ?", connection)
Dim param As OleDbParameter
' add first date '
param = New OleDbParameter()
param.DbType = DbType.Date
param.Value = New DateTime(1800, 1, 1)
cmd.Parameters.Add(param)
'add second date '
param = New OleDbParameter()
param.DbType = DbType.Date
param.Value = DateTime.Today.AddDays(-a)
cmd.Parameters.Add(param)
cmd.Parameters.Add(New OleDbParameter())
connection.Open()
Using adapter As New OleDbDataAdapter(cmd)
Using ds As New DataSet()
adapter.Fill(ds)
Console.WriteLine(ds.Tables(0).Rows.Count)
End Using ' DataSet '
End Using ' OleDbDataAdapter '
End Using ' OleDbCommand '
End Using ' OleDbConnection '
Can you not change the Sqlstr to
SQLstr = " Select * from tb where lastvstart <= '" & b.ToString("dd MMM yyyy") & "'";
EDIT, change based on DB
Use this string and check if it works
SQLstr = " Select * from tb where lastvstart <= #" & b.ToString("dd MMM yyyy") & "#";