How to retrieve the data from Database in VB.net
I am using
SELECT* FROM tbl1 WHERE Col1 = 'Chaitra'
My requirement is there is one Textbox, I have retrieved text from that textbox & assigns to a variable called str1.
Now I have to compare this variable with database (SELECT* FROM tbl1 WHERE Col1 = str1).
Can we write like this? or is there any other way to do this?
Use parameters to prevent Sql-Injection
Dim t As New DataTable()
Using c As New SqlConnection(connectionString)
c.Open()
Using a As New SqlDataAdapter("SELECT* FROM tbl1 WHERE Col1 = #Col1", c)
'use the appropriate SqlDbType'
a.SelectCommand.Parameters.Add("#Col1", SqlDbType.NChar, 5, "Col1")
a.SelectCommand.Parameters("#Col1").Value = str1
a.Fill(t)
End Using
End Using
Return t
Edit: according to your comment that you want to query MS Access
Dim t as New DataTable
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
Dim command As OleDbCommand
Using connection As New OleDbConnection(connectionString)
' Create the SelectCommand.
command = New OleDbCommand("SELECT * FROM Users " & _
"WHERE UserName = ?", connection)
command.Parameters.Add("UserName", OleDbType.VarChar, 20).Value = userName 'userName is a string variable
adapter.SelectCommand = command
connection.Open()
adapter.Fill(t) 't is the DataTable that holds all columns of the User
End Using
http://msdn.microsoft.com/en-us/library/bbw6zyha.aspx
Related
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)
I am trying to create a system that will load items from a database. There are two comboboxes; combobox1 which loads items from database table 1 and combox2 which loads items from database table 2.
Both tables are in the same database.
Here is was I tried but when I run the system I get this error:
(Conversion from string "SELECT * FROM dbo.Dishes" to type 'Long' is not valid.)
Here is the code I'm using:
Dim connection As New SqlConnection("Server = DESKTOP-1373H91; Initial Catalog = MealPreOrderSystem; Integrated Security = True")
connection.Open()
Dim query As String = "SELECT * FROM dbo.Dishes" And "SELECT * FROM dbo.Desserts"
Dim cmd As SqlCommand
cmd = New SqlCommand(query, connection)
Dim reader As SqlDataReader
reader = cmd.ExecuteReader
While reader.Read
cbxType.Items.Add(reader.Item("MealName"))
cbxType.Items.Add(reader.Item("DessertName"))
End While
connection.Close()
In VB.NET,AND is an operator.It is used to perform conjunction between either Booleans or Integers/Doubles/any numeric expression.Lets take your query string as an example :
Dim query As String = "SELECT * FROM dbo.Dishes" And "SELECT * FROM dbo.Desserts"
You are using AND here to join 2 sentences/strings which wouldn't result in anything rather it is trying to cast it as a Long.
Try to execute this command in SQL and you won't find any luck :(.
Your statements are correct :
SELECT * FROM dbo.Dishes
SELECT * FROM dbo.Desserts
But the way you are trying to achieve your goals is incorrect :(.
To get the data from the database into your combobox, what you can do is either use two comboboxes with separated SQL Queries/SQL Commands or you can use one combobox where you add data from both the databases but separate them with some special characters such as a comma ,
A sample may look like :
With one combobox
Dim cmd1 as new SqlCommand("SELECT * FROM dbo.Dishes",connection)
Dim dr as SqlDatareader = cmd1.ExecuteReader
While dr.Read
mycombo1.Items.Add(dr(0)) ' Here 0 is the column count,change it as required
End while
Dim cmd2 as new SqlCommand("SELECT * FROM dbo.Desserts",connection)
Dim dr2 as SqlDatareader = cmd2.ExecuteReader
While dr2.Read
mycombo2.Items.Add(dr2(0)) ' Here 0 is the column count,change it as required
End while
With 1 combobox
Here it gets a bit complicated.Firstly you need to populate your combobox from the data received from the first dataReader.Then, when the 2nd datareader is reading the data , you need to update the existing data/Item of the combobox keeping the existing data/item but adding new data/item to each existing data/item(separating them with ,).
Sample :
Dim i as Integer
Dim cmd1 as new SqlCommand("SELECT * FROM dbo.Dishes",connection)
Dim dr as SqlDatareader = cmd1.ExecuteReader
While dr.Read
mycombo1.Items.Add(dr(0))
End while
Dim cmd2 as new SqlCommand("SELECT * FROM dbo.Desserts",connection)
Dim dr2 as SqlDatareader = cmd2.ExecuteReader
While dr2.Read
mycombo1.Items(i) = myconbo1.Items(i) & "," & dr2(0)
i = i + 1
End while
Now, NOTE THAT I AM USING MULTIPLE DATAREADERS WITH THE SAME CONNECTION ,SO YOU MAY NEED TO INCLUDE MultipleActiveResultSets=True IN YOUR CONNECTION STRING or ENCLOSE THE DATAREADERS IN USING STATEMENTS or CALL dataReader.Close AFTER EACH DATAREADER HAS COMPLETED READING FROM THE DATABASE
This will solve your issue :)
Looks like you don't know how to write SQL queries (and your VB syntax itself looks faulty - string AND string?).
Dim connection As New SqlConnection("Server = DESKTOP-1373H91; Initial Catalog = MealPreOrderSystem; Integrated Security = True")
Dim query As String = <cmdString>
SELECT MealName as Name FROM dbo.Dishes
union
SELECT DessertName as Name FROM dbo.Desserts
</cmdString>
Dim cmd As SqlCommand
Dim reader As SqlDataReader
connection.Open()
cmd = New SqlCommand(query, connection)
reader = cmd.ExecuteReader
While reader.Read
cbxType.Items.Add(reader.Item("Name"))
End While
connection.Close()
Note: You are saying 2 comboboxes but your code seemed to be loading all the items to a single combobox. If you really need 2 comboboxes then use 2 SqlCommand and Reader loops (actually it would be better if you simply have used Linq for this).
You should be a bit more specific on what columns you are pulling from the 2 tables. if they are similar, you could write a sql query to UNION ALL the fields with a simple control to identify which record came from which table.
Example of SQL command string:
"SELECT 'M' AS Ctl, MealName AS aName FROM dbo.Dishes " &
"UNION ALL " &
"SELECT 'D' AS Ctl, DessertName AS aName FROM dbo.Desserts"
As mentioned by many here already, it seems like you are referencing only 1 ControlBox to list the fields returned cbxType
below is the reader (adapted to 2 ComboBoxes):
While reader.Read
Select Case reader.Item("Ctl")
Case "M"
cbxMType.Items.Add(reader.Item("aName"))
Case "D"
cbxDType.Items.Add(reader.Item("aName"))
End Select
End While
Hope this helps
studentname = TextBox1.Text
Dim connection As SqlCeConnection
Dim cmdString = "INSERT INTO [student](studentname) values(#studentname)"
Dim cmdString1 = "select * from student"
connection = New SqlCeConnection("Data Source=gandharva.sdf")
connection.Open()
Dim command As SqlCeCommand
Dim command1 As SqlCeCommand
command = New SqlCeCommand(cmdString1, connection)
command1 = New SqlCeCommand(cmdString, connection)
command1.Parameters.Add("#studentname", studentname)
r = command1.ExecuteNonQuery()
Dim reader As SqlCeDataReader
reader = command.ExecuteReader(CommandBehavior.CloseConnection)
Dim stdpaswd As String
While reader.Read()
stdpaswd = reader("studentname").ToString()
MsgBox(stdpaswd)
End While
connection.Close()
End Sub
THE DATABSE IS LIKE THIS
studentname
kartik
abhi
NULL
I am writing a database code to insert records using insert query.
The code works fine but there is no modified data in the table, its left with only the data entered manually to the table.
also in the messagebox it shows the the data inserted with insert query.
but the table is left with only 2 names which i have created manually.
Please help how to modify so that the table will have the entered data through the query?
This is a new concept for me and I can't quite see what's causing the error
I'm attempting to populate a datagridview control from a single field in an Access database (from a combo and Text box source).
Using literals works, but not with the parameter.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Backend & ";Persist Security Info=False;")
Dim command As New OleDbCommand("Select Year from tblTest ", conn)
Dim criteria As New List(Of String)
If Not cboYear.Text = String.Empty Then
criteria.Add("Year = #Year")
command.Parameters.AddWithValue("#Year", cboYear.Text)
End If
If criteria.Count > 0 Then
command.CommandText &= " WHERE " & String.Join(" AND ", criteria)
End If
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
Dim UserRet As New DataTable
UserQuery.Fill(UserRet)
With frmDGV.DataGridView2
.DataSource = UserRet
End With
frmDGV.DataGridView2.Visible = True
frmDGV.Show()
Trying to Fill the datatable shows exception 'No value given for one or more required parameters.'
The value of command.CommandText at that point is "Select Year from tblTest WHERE Year = #Year"
Your instance of OleDbDataAdapter was created using two parameters query text and connection.
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
In this case DataAdapter doesn't know about parameters at all.
Instead use constructor with paremeter of type OleDbCommand.
Dim UserQuery As New OleDbDataAdapter(command)
In your code instance of OleDbCommand already associated with connection
This is what I've got so far :
Dim myCONN As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\Baza.mdb")
Dim cmd1 = New OleDbCommand("SELECT ID FROM Baza WHERE NAZIV=#XXNAZIV")
cmd1.Parameters.AddWithValue("#XXNAZIV", TextBox2.Text)
cmd1.Connection = myCONN
myCONN.Open()
Dim result = cmd1.ExecuteReader()
While (result.Read())
Dim rowx As Integer = GetTextOrEmpty(result("ID"))
End While
I've found the row (rowx) in which I would like to change values in 20 corresponding columns (namesID : NAZIV, SIFRA,...). Data is already presented in textboxes (textbox1...), but I don't know how to finish this code with UPDATE and how to insert changed values back to Access.
Dim cmdText As String = "UPDATE Baza SET NAZIV=#XXNAZIV Where ID=SomeId"
Using con = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = h:\Baza.mdb")
Using cmd = new OleDbCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#XXNAZIV",TextBox2.Text)
cmd.ExecuteNonQuery()
End Using
End Using
This should help you to solve your problem, of course you will have to pass ID parameter to query also.
Reference