how to get datatable if textbox matches your data in database - vb.net

how can I possibly populate my table if like textbox.text matches from my data inside database.
I'm stuck here, not sure where I did go wrong
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim dbcommand As String
dbcommand = "SELECT * FROM aws_rdp where csn_user like " & txtCSNUser.Text & ""
adt = New OleDbDataAdapter(dbcommand, dbconn)
datatable = New DataTable
adt.Fill(datatable)
DataGridView1.DataSource = datatable
End Sub

Try putting ' before and after the quotation marks surrounding the textbox text. If you're trying to find that text within the text stored in the database you will also need wildcards (%) surrounding it too. Try:
dbcommand = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Also, as others have stated, look into using parameters in your SQL code as it will help prevent things like SQL injection and is always good practice

Found the answer to my problem by using this code. Anyways, thanks for your time replying on my query, will surely take note of your advises for my future references
Dim dbcommand As String = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Dim command As New OleDbCommand(dbcommand, dbconn)
Dim adapter As New OleDbDataAdapter(command)
Dim datatable As New DataTable
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Columns(0).HeaderText = "ID"
DataGridView1.Columns(1).HeaderText = "IP Address"
DataGridView1.Columns(2).HeaderText = "Username"
DataGridView1.Columns(3).HeaderText = "Password"

Related

Updating database with BindingSource data

This is my first post in here, but this forum already helped me a lot.
First, sorry for my English, i'm from Brazil and i'm trying to write without a translator.
I'm developing a software for a supermarket, but i'm having problems with the connection to the database. I'm trying to make all the connections and transactions programmatically (DataSets, BindingSources and so).
I've already managed to connect with SQL Server Express 2008, using a Function ("consulta") inside a Module ("db"):
Dim ad As SqlDataAdapter = New SqlDataAdapter
Function consulta(ByVal tabela As String, Optional opt As Boolean = False, Optional optparam As String = "") As DataSet
Dim ds As New DataSet
Try
Dim connstring As String = "Data Source=NOTEBOOK\SQLEXPRESS;Initial Catalog=SysMarket;Persist Security Info=True;User ID=admin;Password=XXXXXX"
Dim conObj As New SqlConnection(connstring)
Dim sql As String
If opt = True Then
sql = "SELECT * FROM " & tabela & " " & optparam
Else
sql = "SELECT * FROM " & tabela
End If
Dim cmd As SqlCommand = New SqlCommand(sql, conObj)
ad.SelectCommand = cmd
conObj.Open()
ad.Fill(ds, tabela)
ad.Dispose()
cmd.Dispose()
conObj.Close()
Return ds
Catch ex As Exception
MessageBox.Show("Erro na consulta" & vbCrLf & ex.InnerException.ToString, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
ds.Clear()
Return ds
End Try
End Function
And this is a part of the main code where I make a SelectQuery and put into a BindingSource:
Dim ds As DataSet = db.consulta("departamentos")
Private Sub cad_departamento_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BindingSource1.DataSource = ds
BindingSource1.DataMember = "departamentos"
TextBox1.DataBindings.Add("Text", BindingSource1, "id")
TextBox2.DataBindings.Add("Text", BindingSource1, "departamento")
End Sub
But my problem is when I have to Update the database, by adding, editing or deleting some item from BindingSource. Because in the Module I've closed the connection to the SQL Server. So I will need reopen this connection and then, somehow "read" the DataSet with the change and Update the database?
Someone could explain this to me or show me a example?
Thank you.
You will use a data adapter to save the data, just as you used one to retrieve the data. You will have to create an InsertCommand if you want to insert new records, an UpdateCommand if you want to update existing records and a DeleteCommand if you want to delete existing records. You can write those yourself or, if the conditions are right, you can use a command builder to do it for you.
If your query is based on a single table and you want to insert/update all the columns you retrieve back to that same table then a SqlCommandBuilder may be your best bet. You simply pass in the query and the command builder will use it to generate the action commands. That gives you limited flexibility but if you're just doing single-table operations then you don't need that added flexibility.
Such a method might look something like this:
Public Sub SaveChanges(tableName As String, data As DataSet)
Dim query = "SELECT * FROM " & tableName
Using adapter As New SqlDataAdapter(query, "connection string here")
Dim builder As New SqlCommandBuilder(adapter)
adapter.Update(data, tableName)
End Using
End Sub
I did what you said, but when I open the Form again, the new data are not there.
I made some changes in the code, perhaps because it did not work
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
BindingSource1.EndEdit()
ds.AcceptChanges()
db.SaveChanges("departamentos", "INSERT INTO departamentos VALUES('', " & TextBox2.Text & ")", ds)
ds = db.consulta("departamentos")
End Sub
And the code in the Module
Function SaveChanges(tableName As String, query As String, data As DataSet)
Using adapter As New SqlDataAdapter(query, "Data Source=NOTEBOOK\SQLEXPRESS;Initial Catalog=SysMarket;Persist Security Info=True;User ID=admin;Password=XXXXX")
Dim builder As New SqlCommandBuilder(adapter)
adapter.Update(data, tableName)
Return True
End Using
End Function

Show SQL Column Item in VB.NET TextBox

I want a specific value of an SQL Database column to appear in a textbox, but there is an error with my code which appears to be at this line:
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
Imports MySql.Data.MySqlClient
Public Class Main
Dim conn As MySqlConnection
Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load
conn = New MySqlConnection()
conn.ConnectionString = "server='127.0.0.1';user id='root';Password='test';database='snipper'"
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
Dim strSQL As String = "SELECT * FROM snippets"
Dim da As New MySqlDataAdapter(strSQL, conn)
Dim ds As New DataSet
da.Fill(ds, "snippets")
With ComboBox1
.DataSource = ds.Tables("snippets")
.DisplayMember = "title"
.SelectedIndex = 0
End With
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title=" & cbSnippets.Text)
cmd.Connection = conn
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
While lrd.Read()
txtCode.Text = lrd("snippet").ToString()
End While
End Sub
What may be wrong?
PLEASE USE PARAMETERISED QUERIES
Your actual problem originates from this line:
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title=" & cbSnippets.Text)
Supposing I enter "This is a test" into the text box, the SQL becomes
SELECT snippet
FROM snippets
WHERE title=This is a test
With no quotes around the text, it should be:
SELECT snippet
FROM snippets
WHERE title='This is a test'
However, if I were to write "''; DROP TABLE Snippets; -- " In your text box you may find yourself without a snippets table!.
You should always use parameterised queries, this is safer and more efficient (it means query plans can be cached and reused so don't need to be compiled each time);
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title = #Title")
cmd.Parameters.AddWithValue("#Title", cbSnippets.Text)
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
Try changing this line :
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title=" & cbSnippets.Text)
to :
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title='" & cbSnippets.Text & "'")
Note the quotes around the string you'l be searching for. You could aswell use the like comparison too :
Dim cmd = New MySqlCommand("SELECT snippet FROM snippets where title like '%" & cbSnippets.Text & "%'")
The % symbol acts as a wildcard. In this case, that would look for any string containing the searched text instead of string being exactly the same as the searched text.

How can I filter without redundant display to combobox?

hmm this is my problem, How can I prevent double display in my Combobox if i have a datatable
"Student" with column "Section" inside is BE701P, BE101P, BE701P, BE701P, BE101P.
I want to display only to combobox the "BE701P and BE101P" like this preventing redundant display, is it possible?
Private Sub section()
Try
conn = New OleDbConnection(Get_Constring)
Dim sSQL As String = ("SELECT [section] FROM student where username like'" & Administrator.lblusername.Text & "%' ")
Dim da As New OleDbDataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds)
cmbsection.ValueMember = "section"
cmbsection.DataSource = ds.Tables(0)
cmbsection.SelectedIndex = 0
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
it will display all data into combobox and makes redundant display. as i want to prevent redundancy. I would be very glad to any suggestions.
Why not use DISTINCT in your sql query like:
Dim sSQL As String = ("SELECT DISTINCT [section] FROM student
where username like'" & Administrator.lblusername.Text & "%' ")
See link here for mysql examples (although you did not specify your DBMS).
You can create a DataTable from the default DataView of your DataTable that show distinct records only. The advantage of using this approach is that you can keep all records in your original DataTable (which may be used for some other binding). Also note that this is a client-side operation, so you can save your server some processing effort if there are many clients doing this.
The syntax would be something like:
ds.Tables(0).DefaultView.ToTable(True, {"section"})

Search multiple results from database and display in single textbox

guys i want to build an efficient searching tool in vb to search data from my database in mysql where i have stored paragraphs of some information. i want the search to return multiple results like google does but in a textbox in the form of 2-3 paragraphs of the same concept.Also to make the search more efficient i want to include the substring feature that is the % sign in the select query. can anyone tell me how to implement these two features ? here is my basic search code that returns just a single paragraph stored in the table into my result textbox that i hide first and then show when the results appear.
If TextBox1.Text = "" Then
MsgBox("Please Enter a Keyword")
Else
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "Server=localhost;UserID=root;Password=admin674;Database=db1"
Dim myadapter As New MySqlDataAdapter
conn.Open()
Dim sqlquery = "select text from text where name like '" & TextBox1.Text & "'"
Dim mycommand As New MySqlCommand
mycommand.Connection = conn
mycommand.CommandText = sqlquery
myadapter.SelectCommand = mycommand
Dim mydata As MySqlDataReader
mydata = mycommand.ExecuteReader
If mydata.HasRows = 0 Then
MsgBox("Data Not Found")
TextBox1.Clear()
TextBox2.Clear()
Else
mydata.Read()
TextBox2.Text = mydata.Item("text")
TextBox2.Show()
End If
You already answered one question yourself - how to do a substring search, simple add % to your query:
Dim sqlquery = "select text from text where name like '%" & TextBox1.Text & "%'"
(ideally, instead of supplying search value in-line you would use parametrized query, which, among other things would help avoid SQL Injection.
As for the second part - you are already using DataReader, all you have to do is instead using a single mydata.Read() command - loop thru all its results. Replace
mydata.Read()
TextBox2.Text = mydata.Item("text")
TextBox2.Show()
with
Dim sb as New StringBuilder()
While mydata.Read()
sb.AppendLine(mydata("text"))
End While
TextBox2.Text = sb.ToString()
TextBox2.Show()
This approach uses StringBuilder class which is an efficient way to concatenate multiple strings.
P.S. Don't forget to close your DataReader and Connection after use.

SQL like with multiple textboxes

For my company I have to create a customer database, which I manage over a VB.NET application.
The application has a few textboxes and a button to "Search" for a customer. If I type in the name of a customer the SQL Select statement is working and populating my datagrid.
But I want to be able to type in the name of the customer AND the street where he lives in. What is the best solution for this? using cases? using a lot of If statements?
Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If True Then
Dim Conn As New MySqlConnection
Dim da As MySqlDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim plz As String = plzTextBox.Text
Conn.ConnectionString = "server=localhost;uid=root;pwd=;database=wws; "
Dim sql As String = String.Empty
If vornameTextBox.Text <> String.Empty Then
sql = "vorname = " & vornameTextBox.Text.Trim
End If
If nachnameTextBox.Text <> String.Empty Then
AddCondition(sql, "nachname LIKE '%" & nachnameTextBox.Text.Trim & "%'")
End If
If emailTextBox.Text <> String.Empty Then
AddCondition(sql, "email LIKE '%" & emailTextBox.Text.Trim & "%'")
End If
If plzTextBox.Text <> String.Empty Then
AddCondition(sql, "plz LIKE '%" & plzTextBox.Text.Trim & "%'")
End If
If sql <> String.Empty Then
da = New MySqlDataAdapter("SELECT id,vorname,nachname,email,plz,strasse,nummer,stiege,stock,tuer FROM kunden WHERE " + sql, Conn)
da.Fill(dt)
DataGridView1.DataSource = dt
End If
Else
DataGridView1.ColumnCount = 1
DataGridView1.Rows.Add("1")
End If
End Sub
Thanks in advance!
You can avoid using lots of if statements if you really want, but all you're doing is shunting a load onto your SQL server instead of having it on the client.
The example here is one where you can use lots of if statements or ternary operators to determine how you build your SQL statement, putting a very light processing load on the client, or you can just insert the text value of each of your fields, followed by a percentage sign and surrounded by single quotes, thus making your SQL server evaluate the contents of those fields when it otherwise wouldn't if the field is blank.
It's possible query plan optimization would remove those superfluous field searches, and maybe it wouldn't. I'm typing this on my phone and so don't have anything available to test with.