need to get value from sql query - vb.net

Through ADO,I like to do the following query:
select name, address, zip from terr where id = '33334'
I like then to assign name, addess, zip to variables so that I can assign it later in my program.
How do I do this with VB.NET ADO?

Try somethign like this:
Dim dbName As String
Dim dbAddress As String
Dim dbZip As String
Using connObj As New SqlClient.SqlConnection("<connectionString>")
Using cmdObj As New SqlClient.SqlCommand("select name, address, zip from terr where id = '33334'", connObj)
connObj.Open()
Using readerObj As SqlClient.SqlDataReader = cmdObj.ExecuteReader
'This will loop through all returned records
While readerObj.Read
dbName = readerObj("name").ToString
dbAddress = readerObj("address").ToString
dbZip = readerObj("zip").ToString
'handle returned value before next loop here
End While
End Using
connObj.Close()
End Using
End Using
Also, you should look into parameterizing the value for the where clause.

You need a DataBase (i assume MS Sql-Server), a Connection and a DataAdapter to fill a DataTable. Then you have all you need. Here's an example:
Public Function GetUser(UserId As Int32) As DataRow
Using con = New SqlConnection(My.Settings.RM2ConnectionString)
Using cmd = New SqlCommand("select name, address, zip from terr where id = #id", con)
cmd.Parameters.AddWithValue("#id", UserId)
Dim da = New SqlDataAdapter(cmd)
Dim tblUser = New DataTable
da.Fill(tblUser)
If tblUser.Rows.Count <> 0 Then
Return tblUser(0)
Else
Return Nothing
End If
End Using
End Using
End Function

execute a SqlCommand from SQLDatareader, like:
Dim vVendedor As New SqlCommand("SELECT user FROM users", mConeccion)
vDatosVen = vVendedor.ExecuteReader
vVendedor = Nothing
and to get te value:
While vDatosVen.Read()
vUser = vDatosVen("user")
End While

Here's what i did...
Private Sub btn_Connect_Click(sender As Object, e As EventArgs) Handles btn_Connect.Click
Dim sql_connection As New MySqlConnection
Dim sql_query As New MySqlCommand
Dim sql_result As MySqlDataReader
sql_connection.ConnectionString = "Server=localhost;Database=hidden;Uid=root;Pwd=;"
sql_query.Connection = sql_connection
sql_connection.Open()
sql_query.CommandText = "SELECT Entry,name FROM table WHERE entry=1;"
sql_result = sql_query.ExecuteReader
If sql_result.HasRows Then
Do While sql_result.Read()
Dim query_result As String
query_result = sql_result("name")
MsgBox(query_result)
Loop
Else
MsgBox("No results found.")
End If

Related

Data not showing up in DataGridView after a search query

Hello i am trying to search for data from a table using a funcion, however when i Input the number of the customerID it doesnt show up in the data gridview but the data is still passed to my textboxes. Could anyone help me in explaining what I did wrong?
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = Fname
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customers")
dt = newds.Tables(0)
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
dgvCustomerInfo.DataSource = dt
con.Close()
End Using
Return dt
End Function
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
If txtSearchName.Text <> "" Then
SearchData(txtSearchName.Text, "0")
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
ElseIf txtSearchID.Text <> "" Then
SearchData("0", txtSearchID.Text)
Dim dt = GetSearchResults(txtSearchID.Text)
dgvCustomerInfo.DataSource = dt
End If
End Sub
Try to think about what each line of code is doing. See in line comments
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
'Delete this line - there is no need for a Dataset
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open() 'Move this line - don't open the connection until directly before the .Execute...
'The Like operator would expect a pattern to match
'The interpolated string with the percent signs add wildcard characters
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
'Delete - We don't need a DataAdapter
Dim da As New SQLiteDataAdapter(cmd)
'Delete - We already have a filled DataTable
da.Fill(newds, "customers")
'Delete - same as above
dt = newds.Tables(0)
'Delete - Have no idea what this does. You are already going to display your data in a grid
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
'Delete - You will set the DataSource in the User Interface code
dgvCustomerInfo.DataSource = dt
'Delete - End Using closes the connection and disposes the connection and command.
con.Close()
End Using
Return dt
End Function
The corrected code will look like this.
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
In the user interface code I have added in line comments.
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
'Declare the DataTable outside the If block
'We do not need a New DataTable because SearchData is returning a DataTable
Dim dt As DataTable
If txtSearchName.Text <> "" Then
'Call only one function to return the DataTable
'SearchData is expecting 2 parameters, a String and an Integer
'Putting 0 in quotes makes it a String
dt = SearchData(txtSearchName.Text, 0)
'I removed the DataSource, Don't repeat yourself
'Assign it once after the If
ElseIf txtSearchID.Text <> "" Then
'The second argument must be an Integer, therefore the CInt()
dt = SearchData("", CInt(txtSearchID.Text))
Else
'Needed to add an Else to assign a value to dt if all else fails
dt = Nothing
End If
dgvCustomerInfo.DataSource = dt
End Sub

Check if Row is already exist in table before inserting

Well its been a while since my last post about saving loops through checkboxlist.So I did manage to check the input before it saved into table, but somehow it couldnt save any data even if wasnt duplicate one.
Wanted to create a function to check if each checkboxlist is already present within the table but I cant manage it because it needs value from this script so I skip it.
Using conn2 As New SqlConnection()
conn2.ConnectionString = ConfigurationManager _
.ConnectionStrings("BackboneConnectionString").ConnectionString()
Using cmd As New SqlCommand
cmd.CommandText = "Insert into EL_MstFunctionalNilai values(#IDFunc, #nik, #IDFuncParent, #IDFuncChild, #IDFuncMtr, '', '', '0')"
cmd.Connection = conn2
conn2.Open()
For Each item As ListItem In CheckBoxList2.Items
If item.Selected Then
'cmd.Parameters.Clear()
Dim urutan As Int32 = GetNumberFunctional()
Dim str As String = item.Value.ToString
Dim strArr() As String = str.Split("_")
Dim IDFunctionalParent1 As String = strArr(0)
Dim IDFunctionalChild1 As String = strArr(1)
Dim IDFunctionalMtr1 As String = strArr(2)
cmd.CommandText = "select count(*)as numrows from el_mstFunctionalnilai where nik = #nik and idfuncmtr = #IDFuncMtr"
cmd.Parameters.AddWithValue("#nik", txtnik.Text)
cmd.Parameters.AddWithValue("#IDFuncMtr", IDFunctionalMtr1)
queryresult = cmd.ExecuteScalar()
If queryresult = 0 Then
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#IDFunc", urutan)
cmd.Parameters.AddWithValue("#nik", txtnik.Text)
cmd.Parameters.AddWithValue("#IDFuncMtr", IDFunctionalMtr1) 'mtr
cmd.Parameters.AddWithValue("#IDFuncParent", IDFunctionalParent1) 'parent
cmd.Parameters.AddWithValue("#IDFuncChild", IDFunctionalChild1) 'child
cmd.ExecuteNonQuery()
'Label1.Text = queryresult --> already check if queryresult has value
End If
End If
Next
conn2.Close()
End Using
End Using
When its executed no error tho, so I cant figure it out what Im missing. Well how do I fix this up?
Thanks.
el_mstFunctionalnilai
EL_MstFunctionalNilai
Which is it? Be careful about capitalization.
I have guessed at all the SqlDbType Please check your database to get the actual types.
Code following your pattern with 2 hits to database.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim queryResult As Integer
'Pass the connection string directly to the constructor of the connection
Using conn2 As New SqlConnection(ConfigurationManager.ConnectionStrings("BackboneConnectionString").ConnectionString())
'Pass the command text and the connection directly to the command constructor
'You do not need as alias for Count
Using cmd As New SqlCommand("select count(*) from EL_MstFunctionalNilai where nik = #nik and idfuncmtr = #IDFuncMtr", conn2)
conn2.Open()
'This value does not appear to change in the loop so I moved it outside the loop
Dim urutan As Int32 = GetNumberFunctional()
'Add the parameters outside of the loop and only change the value inside the loop
'The value of the text box can't change inside the loop so it can be assigned outside the loop
cmd.Parameters.Add("#nick", SqlDbType.Int).Value = CInt(txtnik.Text)
cmd.Parameters.Add("#IDFuncMtr", SqlDbType.VarChar)
Using cmd2 As New SqlCommand("Insert into EL_MstFunctionalNilai values(#IDFunc, #nik, #IDFuncParent, #IDFuncChild, #IDFuncMtr, '', '', '0')", conn2)
cmd2.Parameters.Add("#IDFunc", SqlDbType.Int).Value = urutan
cmd2.Parameters.Add("#nik", SqlDbType.Int).Value = CInt(txtnik.Text)
cmd2.Parameters.Add("#IDFuncMtr", SqlDbType.VarChar) 'mtr
cmd2.Parameters.Add("#IDFuncParent", SqlDbType.VarChar) 'parent
cmd2.Parameters.Add("#IDFuncChild", SqlDbType.VarChar) 'child
For Each item As ListItem In CheckBoxList2.Items
If item.Selected Then
Dim str As String = item.Value.ToString
Dim strArr() As String = str.Split("_"c)
Dim IDFunctionalParent1 As String = strArr(0)
Dim IDFunctionalChild1 As String = strArr(1)
Dim IDFunctionalMtr1 As String = strArr(2)
cmd.Parameters("#IDFuncMtr").Value = IDFunctionalMtr1
queryResult = CInt(cmd.ExecuteScalar())
If queryResult = 0 Then
cmd2.Parameters("#IDFuncMtr").Value = IDFunctionalMtr1 'mtr
cmd2.Parameters("#IDFuncParent").Value = IDFunctionalParent1 'parent
cmd2.Parameters("#IDFuncChild").Value = IDFunctionalChild1 'child
cmd.ExecuteNonQuery()
End If
End If
Next
End Using
End Using
End Using
End Sub
I think it would be easier using one query that both checks for the existence of the record and inserts it if it doesn't exist.
Protected Sub Method2()
Dim urutan As Int32 = GetNumberFunctional()
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("BackboneConnectionString").ConnectionString())
Using cmd As New SqlCommand("If Exists (Select 1 From EL_MstFunctionalNilai where nik = #nik and idfuncmtr = #IDFuncMtr) Select 0 Else Select 1 Insert into EL_MstFunctionalNilai values(#IDFunc, #nik, #IDFuncParent, #IDFuncChild, #IDFuncMtr, '', '', '0');", cn)
cmd.Parameters.Add("#nik", SqlDbType.Int).Value = CInt(txtnik.Text)
cmd.Parameters.Add("#IDFuncMtr", SqlDbType.VarChar)
cmd.Parameters.Add("#IDFunc", SqlDbType.VarChar).Value = urutan
cmd.Parameters.Add("#IDFuncParent", SqlDbType.VarChar)
cmd.Parameters.Add("#IDFuncChild", SqlDbType.VarChar)
cn.Open()
For Each item As ListItem In CheckBoxList2.Items
If item.Selected Then
Dim strArr() As String = item.Value.ToString.Split("_"c)
cmd.Parameters("#IDFuncMtr").Value = strArr(2)
cmd.Parameters("#IDFuncParent").Value = strArr(0)
cmd.Parameters("#IDFuncChild").Value = strArr(1)
cmd.ExecuteScalar()
End If
Next
End Using
End Using
End Sub

How do I get the value of 'name' col, same way I am getting the rows count?

database name is 'randomTable'
first col name is 'id'
2nd col name is 'name'
How do I get the value of 'name' col, same way I am getting the rows count?
Protected Sub BindGridData()
' Connect to databse and open database file
Dim da As SqlDataAdapter
Dim ds As DataSet = New DataSet()
Dim query As String = "SELECT * FROM [randomTable]"
Dim sqlConn As New SqlConnection(myCon)
Try
sqlConn.Open()
Dim cmd = New SqlCommand(query, myCon)
da = New SqlDataAdapter(cmd)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(da)
da.Fill(ds, "randomTable")
Dim a As Integer = ds.Tables("randomTable").Rows.Count
If a = 0 Then
e.Text = "empty"
End If
'this line is wrong - ???
Dim s As String = ds.Tables("randomTable").Columns("name")
if s = "value1"
'do something
end if
GridView1.DataSource = ds.Tables("randomTable").DefaultView
GridView1.DataBind()
sqlConn.Close()
Catch ex As Exception
End Try
End Sub
If you want the rows Count, you can execute a query tu Database "SElect Count() from randomTable". But in specific what do you want to do?
Either index by a specific row or iterate the row collection e.g.
Dim s As String = ds.Tables("randomTable").Rows(0).Field(Of String)("name")
If s = "value1" Then
'do something
End If
' or
For row As Integer = 0 To ds.Tables("randomTable").Rows.Count
If ds.Tables("randomTable").Rows(row).Field(Of String)("name") = "value1" Then
' do something
End If
Next

Populate ListBox from SQL only items with condition (first character)

I've managed to put all items in a ListBox, also have the first character defined kto, how to insert only those values from List column into Listbox that begin with that character kto.
Just to mention that kto is value from 0 to 9, always a number.
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
cmd.CommandText = "SELECT List FROM Konta"
Dim kto = Left(Label1.Text, 1)
'Label3.Text = kto
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
Try this
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
Dim kto = Left(Label1.Text, 1)
cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
ListBox1.Items.Clear
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
In your while loop, before adding the item in the listbox check the date type of reader("LIST") and add it only if matches the required type.
You can check the type using the following code:
reader.GetFieldType(0)

get single value from sql-query into a textbox

The result of my sql-query is a single value i want display that in a lable but dont know how. I have a solution creating a dataset put the result of the query into that dataset and get it by row(0),column(0) but i guess there is a smarter way doing it.
Private myquery As String
Sub New(ByVal query As String)
myquery = query
End Sub
Public Sub query_Send()
Dim myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
Dim mycmd As SqlCommand = New SqlCommand(Me.myQuery, myconn)
Dim myTable As New DataTable
Dim previousConnectionState As ConnectionState = myconn.State
Try
If myconn.State = ConnectionState.Closed Then
myconn.Open()
Dim myDA As New SqlDataAdapter(mycmd)
myDA.Fill(myTable)
tb.text = **...**
End If
If previousConnectionState = ConnectionState.Closed Then
myconn.Close()
End If
End Try
End Sub
You can use SqlCommand.ExecuteScalar Method
Dim querystr as String = "select value from MyTable where ID=5"
Dim mycmd As New SqlCommand(querystr, connection)
dim value as Object = mycmd.ExecuteScalar()
The value you can put to your textbox. ExecuteScalar returns first value of first row of the resultset (equivalent of row(0).column(0) ) When no record is returned the value is nothing.
Try something more along the lines of:
Using myconn As New SqlConnection("Data Source=DB;Integrated Security=TRUE")
Dim myDA As New SqlDataAdapter()
myDA.SelectCommand = New SqlCommand(myQuery, myconn)
myDA.Fill(myTable)
Return myTable
End Using
Or you can just get ahold of the first item in the first row with
myTable.Rows(0).ItemArray(0).ToString()