mardi 5 mai 2015

Can't get desired output while looping using VB.Net and SQL server

I have the following code, in which I'm trying to loop through a database, extract apartment numbers and meter readings for their heat outputs during a certain year entered by the user.

The output has to be like...

Apartment No. {apartmentNo} - {TotalReading}

Apartment No. {apartmentNo} - {Totalreading} 'second apartment number and so on

The query seems to read only the last data and not the previous ones.

This is my VB.Net code.

    Imports System.Data.Sql
    Imports System.Data.SqlClient

    Public Class AssociationHeating

        Private Sub GetAssociationButton_Click(sender As Object, e As EventArgs) Handles GetAssociationButton.Click
            Dim con As New SqlConnection
            Dim cmd As New SqlCommand
            Dim reader As SqlDataReader
            Dim totalHeating As Integer = 0
            Dim apt_no As Integer = 1

            con.ConnectionString = "Server=10.176.165.29,1433;Database=EnergyDB;User=Clerk;Pwd=12345"
            cmd.Connection = con
            con.Open()
            cmd.CommandText = "SELECT apartment_no,reading FROM HeatMeasurement WHERE association_no = '" & AssociationField.Text 

& "' and year(reading_date) = '" & YearField.Text & "'"
            reader = cmd.ExecuteReader
            If reader.HasRows Then
                Do While reader.Read()
                    If Convert.ToInt32(reader.GetString(0)) = apt_no Then
                        totalHeating += reader.GetInt32(1)
                        'Console.WriteLine("Read data from apartment: " & reader.GetString(0))
                    Else
                        Console.WriteLine("Apartment " & apt_no & " totals: " & totalHeating)
                        apt_no += 1
                        Console.WriteLine("Incremented apt_no by one")
                        totalHeating = 0
                    End If
                Loop
                Console.WriteLine("Apartment " & apt_no & " totals: " & totalHeating)
            Else
                Console.WriteLine("No data found for the year " & YearField.Text)
            End If
            con.Close()
        End Sub
    End Class

The printouts look like this: Apartment 1 totals: 110 Incremented apt_no by one Apartment 2 totals: 0

(There are 2 apartments with meters)

Aucun commentaire:

Enregistrer un commentaire