Reading from a database and using an if statement - vb.net

The program currently reads from the database, but what I am trying to do is try to get the program to read from the database and if the field is empty then output "TBC" and if not then it will show the grade. I'm unsure of how to check what dr.Read is and use an if statement with it.
Sub GradeResult()
Dim dr As OleDbDataReader
Dim cm As New OleDbCommand
Dim cn As New OleDbConnection
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=login.accdb"
cn.Open()
cm.CommandText = "SELECT ArGrade FROM loginDetails WHERE UserName = '" & username & "'"
cm.Connection = cn
dr = cm.ExecuteReader
dr.Read()
Label6.Text = dr.Item("ArGrade")
End Sub

Instead of using an if statement, when the user registers, the program writes TBC into the field.

dr is an instance of the OleDbDataReader class, and Read is one public method of this class. You need to call it in order to start reading the results after a query is executed against the database.
From the OleDbDataReader.Read documentation page:
Advances the OleDbDataReader to the next record.
You need to call it at least once, to get some results.
Returns
Boolean
true if there are more rows; otherwise, false.
Use it to check if you have any results at all or more results as one.
The default position of the OleDbDataReader is before the first record. Therefore, you must call Read to start accessing any data.
In your case you can check if there is any result like this:
Label6.Text = "TBC" ' standard value is no value found
if dr.Read() then ' DB contains any rows
dim arGrade = dr.Item("ArGrage")
if not IsDbNull(arGrade) then ' and the ArGrade has a value
Label6.Text = arGrade
end if
end if
And don't forget to close the reader with dr.Close.

Related

Visual Studio Vb.net loaded dataset from oracle query missing or replacing first row of data

I have a vb.net application program that is suppose to query a oracle/labdaq database and load the dataset into a datatable. For some reason the query works fine and there is no exception thrown, however, when I load the data it seems to be missing the first row. I first noticed the issue when I did a query for a single row and it returned zero rows when I checked the datatable's row amount during debugging. I then compared all my data sets to a data miner application straight from the oracle source and i seems to always be missing one, the first, row of data when I use the application.
here is the code... I changed the query string to something else to maintain company privacy
Private Sub CaqOnSQL(strFileDirect As String)
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("CA_Requisition_Attachments.Internal.ConnectionString").ConnectionString
Dim conn As New OracleConnection With {
.ConnectionString = connString
}
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
conn.Open()
Dim Cmd As New OracleCommand(strQuerySQL, conn) With {
.CommandType = CommandType.Text
}
Dim dr As OracleDataReader = Cmd.ExecuteReader()
dr.read()
Dim dt As New DataTable
dt.TableName = "RESULTS"
dt.Load(dr)
ExcelFileCreation(dt, strFileDirect)
You should remove the line:
dr.read()
The call to Read is what is causing you to skip the first row, when combined with the DataTable Load method.
In addition, I have taken the liberty to make some additional changes to your code for the purposes of Good Practice. When using Database objects like Connection and Command, you should wrap them in Using blocks to ensure the resources are released as soon as possible.
Dim dt As New DataTable()
dt.TableName = "RESULTS"
Using conn As New OracleConnection(connString)
conn.Open()
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
Using command = New OracleCommand(strQuerySQL , conn)
Using dataReader = command.ExecuteReader()
dt.Load(dataReader)
End Using
End Using
End Using
Note: Be wary of Using blocks when using a DataReaderas you may find the connection is closed when you don't want it to be. In this case, the DataReader is used entirely within this function and is safe to use.

How to get selected cell values of last row from SQL database into two labels?

I am trying to get values from selected columns of the last row into label 1 and label 2 when the form is loaded from a SQL database. My code is not working. How can I do this?
My code is here:
Private Sub getvalue()
Dim strConn = "server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=true"
Dim sqlConn = New SqlConnection(strConn)
sqlConn.Open()
Dim sqlcmd As New SqlCommand("select 22ktrate, 21ktrate from ratedata where max(rateid) = #rateid", sqlConn)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
Label1.Text = myreader.Item("22ktrate")
Label2.Text = myreader.Item("21ktrate")
End If
sqlConn.Close()
End Sub
The big thing I noticed is nothing sets the #rateid parameter.
Private Sub getvalue()
Dim conn As String = "server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=true"
Dim sql As String = "select [22ktrate], [21ktrate] from ratedata where max(rateid) = #rateid"
Using sqlConn As New SqlConnection(conn), _
sqlcmd As New SqlCommand(sql, sqlConn)
'This was missing. You need to know what to set for 1234 here.
'I suggest adding it as argument to the method.
sqlcmd.Parameters.Add("#rateid", SqldbType.Int).Value = 1234
sqlConn.Open()
Using myreader As SqlDataReader = sqlcmd.ExecuteReader()
If myreader.Read() Then
Label1.Text = myreader("22ktrate").ToString()
Label2.Text = myreader("21ktrate").ToString()
End If
End Using
End Using
End Sub
I made other structural changes to the code, too, and you should follow this new pattern. The original code in the question had several less-noticeable issues that could eventually cause user-facing issues, such as failing to close the connection if an exception was thrown.
Finally, I saw this in the comments:
i just want last row two selected column values from sql database
There is no ORDER BY clause in that select statement. Without an ORDER BY clause, the order for the rows is undefined and Sql Server is free to give you the rows in any order it finds convenient. There is no meaningful definition for "last row". If this matters, you must add an ORDER BY clause to the sql statement... at which point, you are better off inverting the order and only taking the first record, rather than iterating the entire result set. If it doesn't matter... you're still better of just taking the first row vs iterating the entire set. In either case, you could also add a TOP 1 to the SQL command — if it's even possible to have more than one record match the max(rateid).
Actually, I can see that you're already using the reader to check if it had rows.
Just set the last value AFTER the reader has read.
This assumes that the Order by of your SQL query is correct (asc or desc)
Change this part:
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
Label1.Text = myreader.Item("22ktrate")
Label2.Text = myreader.Item("21ktrate")
End If
sqlConn.Close()
to
While myreader.Read()
Label1.Text = myreader.Item("22ktrate")
Label2.Text = myreader.Item("21ktrate")
End While
sqlConn.Close()

I want to display records in my textbox

When i input the id number of the student in my TextBox, i want the details of that particular students to be displayed in my textbox, without using datagrid. i am using vb.net.
That is my code and i don't understand what's wrong:
cmd.CommandText = "SELECT * from tblsupplier where pro_code = '" & txcode.Text & "'"
dr = cmd.ExecuteReader
txname.Text = dr.item("sup_product")
txprice.Text = dr.Item("sup_price")
First off, you have left your application open to sql injection by adding the value of the textbox inline. Look up this topic please:
http://en.wikipedia.org/wiki/SQL_injection
As for your code, you need to call dr.Read() before you can actually access any properties from your query.
while (dr.Read()) {
// Do stuff
}
Good luck!
It would help if you could provide additional details about the error, friend. Like what SQL you are using, what was the error message, and which event triggers this reader command.
As it stands, it seems you haven't really sent the DataReader to scan the database. You need the While reader.read() loop.
Here is an example, using OLEDB in a function that fetches the data
Note that connstring is my SQL connection string to an Access Database
Dim conn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=MyDatabase.mdb;Jet OLEDB:Database Password=;")
Function Mycheckifexistss(ByVal sqlCMDstring As String)
Dim sqlCmd As New OLEDBCommand(sqlCMDstring, conn)
Dim reader As OLEDBDataReader
Dim result As String = ""
Try
conn.Open()
reader = sqlcmd.ExecuteReader
While reader.Read
result = reader(0) 'this returns the first field of the queried result.
End While
conn.Close()
Return result
Catch ex As Exception
conn.Close() 'the first thing you want to do in an error, is to close the connection first.
MsgBox(ex.ToString)
End Try
End Function

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.

How do I assign the results of an SQL query to multiple variables in VB.NET?

This is my first attempt at writing a program that accesses a database from scratch, rather than simply modifying my company's existing programs. It's also my first time using VB.Net 2010, as our other programs are written in VB6 and VB.NET 2003. We're using SQL Server 2000 but should be upgrading to 2008 soon, if that's relevant.
I can successfully connect to the database and pull data via query and assign, for instance, the results to a combobox, such as here:
Private Sub PopulateCustomers()
Dim conn As New SqlConnection()
Dim SQLQuery As New SqlCommand
Dim daCustomers As New SqlDataAdapter
Dim dsCustomers As New DataSet
conn = GetConnect()
Try
SQLQuery = conn.CreateCommand
SQLQuery.CommandText = "SELECT Customer_Name, Customer_ID FROM Customer_Information ORDER BY Customer_Name"
daCustomers.SelectCommand = SQLQuery
daCustomers.Fill(dsCustomers, "Customer_Information")
With cboCustomer
.DataSource = dsCustomers.Tables("Customer_Information")
.DisplayMember = "Customer_Name"
.ValueMember = "Customer_ID"
.SelectedIndex = -1
End With
Catch ex As Exception
MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OkOnly, "Connection Error !!")
End Try
conn.Close()
End Sub
I also have no problem executing a query that pulls a single field and assigns it to a variable using ExecuteScalar. What I haven't managed to figure out how to do (and can't seem to hit upon the right combination of search terms to find it elsewhere) is how to execute a query that will return a single row and then set various fields within that row to individual variables.
In case it's relevant, here is the GetConnect function referenced in the above code:
Public Function GetConnect()
conn = New SqlConnection("Data Source=<SERVERNAME>;Initial Catalog=<DBNAME>;User Id=" & Username & ";Password=" & Password & ";")
Return conn
End Function
How do I execute a query so as to assign each field of the returned row to individual variables?
You probably want to take a look at the SqlDataReader:
Using con As SqlConnection = GetConnect()
con.Open()
Using cmd As New SqlCommand("Stored Procedure Name", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#param", SqlDbType.Int)
cmd.Parameters("#param").Value = id
' Use result to build up collection
Using dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection Or CommandBehavior.SingleResult Or CommandBehavior.SingleRow)
If (dr.Read()) Then
' dr then has indexed columns for each column returned for the row
End If
End Using
End Using
End Using
Like #Roland Shaw, I'd go down the datareader route but an other way.
would be to loop through
dsCustomers.Tables("Customer_Information").Rows
Don't forget to check to see if there are any rows in there.
Google VB.Net and DataRow for more info.