Im searching for 85 in a database table column. Column values may include as below
" 85" or " 85" or "852" or 385" or 13857 or "85/1" etc....
"SELECT * FROM FullData where (SYNO LIKE '%" + Z1 + "%' OR SYNO LIKE '%" + Z2 + "%'")
This is my code.
Can anyone help me out to get only 85 or parts or 85 that is ( 85/1 85/A etc...)
Thanks in advance
Let's pretend this is an Sql Server database. Your code might look like this.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim dt = GetFullData("85")
DataGridView1.DataSource = dt
End Sub
Private Function GetFullData(SearchString As String) As DataTable
Dim dt As New DataTable
Dim sql = "Select * FROM FullData where SYNO Like #SearchString;"
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#SearchString", SqlDbType.VarChar).Value = $"%{SearchString}%"
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
Return dt
End Using
End Function
Related
Imports System.Data.OleDb
Public Class Form1
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim strSQL As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnsearch.Click
Dim fieldselect As String = ""
Select Case ComboBox1.Text
Case "startYear"
fieldselect = "startYear"
Case "genres"
fieldselect = "genres"
Case "Rating"
fieldselect = "Rating"
End Select
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")
strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"
conn.Open()
da = New OleDbDataAdapter(strSQL, conn)
Dim ds As New DataSet("Movies")
da.Fill(ds, "Movies")
DataGridView1.DataSource = ds.Tables("Movies")
conn.Close()
End Sub
Keep you data objects local so you can control there closing and disposing. Using...End Using blocks do this for you even it there is an error.
Are all your fields in the Select Case the same datatype? If not you will have to adjust the code. If you need help, tell me the datatypes so I can fix the code.
Always use parameters to avoid sql injection. A text box can hold a Drop Table command. Parameters are treated as values not executable code.
If you need to update later in the code, you will need to have a primary key available in your Select.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Since your field name exactly matches the combo text the Case statement is not necessary
Dim fieldselect As String = ComboBox1.Text
Dim dt As New DataTable
Using conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")
Dim strSQL = "SELECT startYear, genres, averageRating FROM basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst Where " & fieldselect & " = #FieldValue;"
Using cmd As New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#FieldValue", OleDbType.VarChar).Value = TextBox1.Text
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
i wanted to use combo box as the filter for my program, i need to filter data from 2 different table. rating has it own table and basic is different table. both of the field mention above does not have any connection.
It's a bit had to help without context but I gave it a try :
I would replace
strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"
With
"SELECT startYear, genres, averageRating " &
"FROM basic.tconst " &
"INNER JOIN Rating.tconst on basic.tconst=Rating.tconst " & fieldselect & "'" & TextBox1.Text & "%'"
To get better help, could you explain how tables Rating and basic works and what fieldselect is ?
i am new to VB. so when i run my program and search for the name . i want to search with any spaces in between. For example i want to search " Brian Tracy" like that
i am quite confused on the string function that would do that. Thank you for your help
This is the code am working on
Dim search As String = txtAuthorsName.Text
'Search Sql For Authors Data
Dim conn As New
OleDb.OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;Data Source=" +
Server.MapPath("~/Access/bookstore.accdb"))
conn.Open()
Dim sql As String = "SELECT AID, authorName, authorSex FROM Authors"
Dim cmd As Object
If searchAuthor.SelectedValue.Equals("Name") Then
If search.Length > 0 Then
Dim keywords As String() = search.Split(" ")
sql = "SELECT * FROM Authors where authorName like '%" & keywords(0) & "%'"
For k As Integer = 1 To keywords.Length - 1
sql += " or authorName Like '%" & keywords(k) & "%'"
Next
End If
cmd = New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#authorName", "%" + txtAuthorsName.Text + "%")
Else
sql += "WHERE authorSex LIKE #authorSex"
cmd = New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#authorSex", "%" + txtAuthorSex.Text + "%")
End If
Dim dbread = cmd.ExecuteReader()
GridView2.DataSource = dbread
GridView2.DataBind()
dbread.Close()
conn.Close()
This is an example on how to filter/search data :
Public Sub FilterData(valueToSearch As String)
'
Dim searchQuery As String = "SELECT * From Users WHERE CONCAT(fname, lname, age) like '%" & valueToSearch & "%'"
Dim command As New SqlCommand(searchQuery, connection)
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
DataGridView1.DataSource = table
End Sub
Private Sub BTN_FILTER_Click(sender As Object, e As EventArgs) Handles BTN_FILTER.Click
FilterData(TextBox1.Text)
Make necessary changes, hope it works
I'm writing a calorie counter tool for my girlfriend...
But I've run in to an issue I really cant figure out...
I have place in my script where I would wanna take some information out from my db...
The specific place in the script thats teasing, is the one that will take out data from a row called "antal" from a table called "items".
One place in my script, I call "navn" from items, and it works perfect...
This other place, it gives me the error that there isn't any data in the row!
My code looks so far like this:
Imports System.Data.OleDb
Private Sub ins_kat_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ins_kat.SelectedIndexChanged
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Privat\MCC\mccdb.mdb")
Con.Open()
Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM items WHERE kat = '" & ins_kat.Text & "' ORDER BY id DESC", Con)
Dim read As OleDbDataReader = command.ExecuteReader()
ins_mad.Items.Clear()
While read.Read()
ins_mad.Items.Add(read.Item("navn")) '<---- This place works!!!
End While
Con.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim ialt_c_counter As String
Dim ialt_c_counter_conv As Decimal
Dim ialt_c_counter_conv2 As Decimal
Dim ialt_counter As String
Dim ialt_final As Decimal
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Privat\MCC\mccdb.mdb")
Con.Open()
Dim command1 As OleDbCommand = New OleDbCommand("SELECT * FROM food WHERE dag = '" & stat_dag.Text & "' AND maaned = '" & stat_maaned1.Text & "' AND aar = '" & stat_aar1.Text & "'", Con)
Dim read1 As OleDbDataReader = command1.ExecuteReader()
While read1.Read()
ialt_c_counter = read1.Item("antal")
ialt_c_counter_conv = System.Convert.ToDecimal(ialt_c_counter)
Dim commandX As OleDbCommand = New OleDbCommand("SELECT * FROM items", Con)
Dim reader As OleDbDataReader = commandX.ExecuteReader()
ialt_counter = reader.Item("antal") '<--- THIS ONE is giving me the error!!
ialt_c_counter_conv2 = System.Convert.ToDecimal(ialt_counter)
ialt_final = (ialt_c_counter_conv / 100 * ialt_c_counter_conv2) + ialt_final
End While
Con.Close()
MsgBox(ialt_final)
End Sub
End Class
By now, I want a MsgBox telling me the result of my algorithm, but I don't even get that far cause of the error message...
I guess the error you see is
InvalidOperationException: Invalid attempt to read when no data is present.
You never call Read() on the OleDbDataReader called reader.
Note how you use a While loop to call Read() for read and read1, but not reader (bad variable names, btw).
I am using MS Access Database. Now I have to update a particular cell value. Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim Presc As New System.Text.StringBuilder
Dim prs As String(), j As Integer
prs = Split(txtPrescription.Text, vbCrLf)
For j = 0 To prs.Length - 1
Presc.Append(prs(j))
Presc.Append(",")
Next
Try
str = Trim(lsvCase.SelectedItems(0).Text)
'MessageBox.Show(str)
Dim con As System.Data.OleDb.OleDbConnection
Dim ds As New DataSet
Dim rea As System.Data.OleDb.OleDbDataReader
con = New OleDb.OleDbConnection
Dim da As New System.Data.OleDb.OleDbDataAdapter
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source= F:\Sowmya Laptop Backups\sowdb1.accdb;"
con.Open()
Dim cmd As OleDb.OleDbCommand = con.CreateCommand
cmd.CommandText = "UPDATE Casehistory set Prescription =' " & Presc.ToString() & "'"
rea = cmd.ExecuteReader
cmd.ExecuteNonQuery()
da.FillSchema(ds, SchemaType.Mapped)
da.Update(ds, "Casehistory")
con.Close()
Catch ex As Exception
Finally
End Try
End Sub
This code updates all the cells in that column. I want to update only the particular cell having Case_ID = str
Where I have to add the WHERE clause (WHERE Case_ID = " & str & "
I would use command parameters, neater and prevents the SQL injection issue. Something like:
cmd.CommandText = "UPDATE Casehistory set Prescription =#Presc WHERE Case_ID = #CaseID"
cmd.Parameters.AddWithValue("#Presc", Presc.ToString())
cmd.Parameters.AddWithValue("#CaseID",str)
As an aside, having all this code in the button click event is less than ideal. You might want to investigate structuring your app in a more maintainable way - perhaps with a Data Layer for example.
The Where clause should be appended to the end of the OleDbCommmand.CommandText, where you define the Update statement.
I have the following code:
Imports System.Data
Imports System.Data.OleDb
Partial Class Dummy
Inherits System.Web.UI.Page
Dim r As OleDbDataReader
Dim con As OleDb.OleDbConnection
Dim cmd As OleDbCommand
Dim cmd1 As OleDbCommand
Dim prev_ob As New List(Of Int64)
Dim cur_ob As Integer
Dim i As Integer = 0
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New OleDb.OleDbConnection("provider=SQLOLEDB;data source=PC;initial catalog=DB1;integrated security=SSPI")
cmd = New OleDbCommand("select single_column from table1 where date_reqd=(SELECT CONVERT(VARCHAR(10),DATEADD(DD, DATEDIFF(DD, 0, GETDATE()), -1),120))", con)
con.Open()
r = cmd.ExecuteReader
While r.Read
prev_ob.Add(Val(r.Item(0)))
End While
cmd = New OleDbCommand("select column1, column2, date_reqd from table1 where date_reqd=(select CONVERT(varchar(10), GETDATE(),120))", con)
r = cmd.ExecuteReader
While r.Read
For i As Integer = 0 To prev_ob.Count - 1
cur_ob = Val(prev_ob(i)) + Val(r.Item(0))
cmd1 = New OleDbCommand("update table1 set column4='" & cur_ob & "' where column2='" & r.Item(1) & "' and date_reqd='" & r.Item(2) & "'", con)
cmd1.ExecuteNonQuery()
i += 1
Exit For
Next
End While
con.Close()
End Sub
End Class
The problem I'm facing is that the update happens correctly only for the first of many values. All the other values are calculated and consequently, updated incorrectly in my table. I am almost certain that the looping is what is causing the problem but have been unable to find a way around it. Please help me correct it.
It looks like this should be a single UPDATE statement. Unfortunately, it's tricky to tell without seeing your actual table structure. First, write a select statement like this (I'm hoping date_reqd is actually a datetime column also):
SELECT
*
FROM
table1 t1a
inner join
table1 t1b
on
t1a.date_reqd = DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),-1) and
t1b.date_reqd = DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),0) and
/* You need other conditions here if there are multiple rows for the same dates
- I'm guessing there are since you're trying to write a loop */
Once you have this query working, remove the first two lines (SELECT *), and replace them with:
UPDATE
t1b
SET
column4 = t1a.single_column + t1b.column1
And you should be done.
I got it myself! :) All I needed to do was:
Dim i as Integer=0
While r.Read
cur_ob = Val(prev_ob(i)) + Val(r.Item(0))
cmd1 = New OleDbCommand("update table1 set column4='" & cur_ob & "' where column2='" & r.Item(1) & "' and date_reqd='" & r.Item(2) & "'", con)
cmd1.ExecuteNonQuery()
cur_ob = 0
i += 1
End While
And it worked! Thanks for your answers/comments and #Damien_The_Unbeliever, I changed my primary queries to include an ORDER BY clause. Thanks for the tip! :)