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

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()

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.

Reading from a database and using an if statement

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.

How can I use multiple connection in If else code blocks?

I want to use multiple connection in if else code block but it's giving the following error when I checked in a Messagebox :
"Argument prompt cannot be converted to string"
Here is my code :
Try
Conn.Open()
Com.CommandText = "Select * FROM Table1 WHERE ID=" & txtID.Text & " AND DOR=#01/01/1900# AND Paid = '0' ORDER BY DOI"
Dr = Com.ExecuteReader
If Dr.Read = True Then
txtInstNo.Text = Dr(2)
txtInstAmount.Text = Dr(4)
Else
If MsgBox("Wait! You're not allowed to do it. Do you still want to continue ? ", MsgBoxStyle.YesNo Or MsgBoxStyle.Question, "Alert") = MsgBoxResult.Yes Then
Try
Dim Con As New OleDbConnection
Dim Comm As New OleDbCommand
Dim Dr2 As OleDbDataReader
Con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database.accdb"
Con.Open()
Comm.Connection = Con
Comm.CommandText = "Select * FROM Table1 WHERE ID=" & txtID.Text & " AND DOR=#01/01/1900# AND Paid = '0' ORDER BY DOI"
Comm.CommandType = CommandType.Text
Dr2 = Comm.ExecuteReader
MsgBox(Dr2) <-- Here I got that error
If Dr.Read = True Then
txtInstNo.Text = Dr(2)
txtInstAmount.Text = Dr(4)
Else
MsgBox("Sorry, no record found",MsgBoxStyle.Exclamation, "Alert")
End If
Dr2.Close()
Con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
Dr.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Your query might be returning entire rows, objects, widgets or whatever. As #Andrew Morton pointed out, it's a Data Reader. It's not going to implicitly convert your result. You'll have to manipulate your reader result and convert it to a string to do anything useful. You'll also have to handle if your DataReader returns a null result, which when converted should be "" an empty string.
If you just want to see what Dr2 contains, you could try MsgBox(CStr(Dr2)). No error handling, if it throws an exception.
There are a few things which could be modified in your code to make it a bit shorter and so easier to track down what is not working. It is easier to isolate a problem if you have the minimal amount of code which shows the problem: How to create a Minimal, Complete, and Verifiable example.
I'll show my suggestion for a minimal amount of code on a new form which should help you narrow down where the problem is, and then I'll go over why I have written it that way and what could be going wrong.
Option Strict On
Option Infer On
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database.accdb"
Dim sql = "SELECT InstNo, InstAmount FROM Table1 WHERE ID = ? AND DOR = #01/01/1900# AND PAID='0' ORDER BY DOI"
' lists to hold the retrieved data
Dim instNos As New List(Of String)
Dim instAmounts As New List(Of String)
' get the data
Using conn As New OleDbConnection(connStr)
Using cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#ID",
.DbType = DbType.String,
.Value = txtID.Text})
conn.Open()
Dim rdr = cmd.ExecuteReader()
While rdr.Read
instNos.Add(rdr.GetString(0))
instAmounts.Add(rdr.GetString(1))
End While
End Using
End Using
' act on the data
If instNos.Count = 0 Then
MsgBox(String.Format("No records were found for ID ""{0}"".", txtID.Text))
Else
txtInstNo.Text = String.Join(vbCrLf, instNos)
txtInstAmount.Text = String.Join(vbCrLf, instAmounts)
End If
End Sub
End Class
The code.
I start with Option Strict On to make sure that all data types match up and I haven't done anything else silly which Visual Studio can point out to me.
I use Option Infer On so that I don't have to type out the type of variables when the compiler can infer what they are.
I used just one Button on the form along with the three named textboxes as we are going for minimal code.
I set up the two strings which are going to be used in one place at the top of the sub because it is easier to maintain the code that way. Normally, you would declare variables just before they are used to minimise their scope.
I specified exactly which columns I want from the database. There is no point retrieving all of them with *. I had to guess what the columns are called - you will need to put in the actual names if they are different.
The result of a query to the database might have more than one record, so I initialise Lists for the data. (Your query has an ORDER BY so I assume that there could be more than one record.)
The Using statement makes sure that resources are released cleanly whatever else happens.
For OleDb, parameters are normally represented by a ?. (If there is more than one, they are all represented by question marks and the parameters must be added in the order in which they are to be put into the query.) I had to guess at the data type for the ID column - please put in the correct type. When you create the parameter, you can still use a meaningful name for it, even though it is ignored by the computer.
Next, the data (if any) is read. I do nothing else at this point except read the data to keep it fast and tidy. I assumed that the data to be retrieved is strings, hence the GetStrings. You should adjust that if required, and also the types of the Lists to match.
Now that the data has been read, I act on it. If there was no data, show an appropriate message, and if there was data then I put it into multiline textboxes to show it. Note that I wrote multiline: if it was a single line textbox then only the last line would be visible. Other ways of displaying it could be more useful, for example a DataGridView - in which case I might have read the data into a DataTable or a list of some class.
What could go wrong.
In your query, you have AND DOR = #01/01/1900# - is this correct?
In your query, you have AND PAID = '0' - is PAID actually a string? If it is a number then it should be AND PAID = 0. (The DB should convert the string "0" to the number zero, but why make it do extra work?)
Now that you have multiline textboxes for the results, you can see if it just happens that the last records found happened to be blank, and are simply not visible in a single-line textbox.
Finally, are you sure it is using the correct database file?

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

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.