我应该将 StoreBillingDetailsToMonthlyTable() 放在哪里才能成功执行它?我试过把它放在表单加载、计时器和付费按钮中

Where should I put the StoreBillingDetailsToMonthlyTable() to successfully execute it? I've tried putting it in Form Load, Timer and Paid Button

提问人:niks 提问时间:5/1/2023 最后编辑:nbkniks 更新时间:5/1/2023 访问量:23

问:

我应该将 StoreBillingDetailsToMonthlyTable() 放在哪里才能成功执行它?我尝试将其放在表单加载、计时器和付费按钮中,但它没有执行,并且月表中没有进行任何更改。我是这方面的初学者,我已经没有想法在哪里放置和执行它。我是否在编码上犯了任何错误,或者只是函数的放置错误?

 Private Sub Bills_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        MysqlConn = New MySqlConnection()
        MysqlConn.ConnectionString = "server=localhost; userid=root; password=root; database=isp_database"
        MysqlConn.Open()

        Dim Query As String
        Query = "SELECT * FROM isp_database.bill_table"
        Command = New MySqlCommand(Query, MysqlConn)

        Dim dt As New DataTable
        dt.Clear()
        DataGridView1.DataSource = dt
        'DataGridView1.DataSource = Nothing

        Using da As New MySqlDataAdapter(Command)
            da.Fill(dt)
            previousRowCount = dt.Rows.Count
        End Using
        Display_Table()
        StoreBillingDetailsToMonthlyTable()
        UpdateStatusToUnpaid()
        UpdateDateDue()

        MysqlConn.Close()

        Timer1.Enabled = True
        ' Set Timer interval (24 hours)
        timer = New Timer()
        timer.Interval = 24 * 60 * 60 * 1000 ' milliseconds
        AddHandler timer.Tick, AddressOf Timer1_Tick
        timer.Start()
    End Sub

    Private Function CheckForNewData() As Boolean
        Dim MysqlConn = New MySqlConnection()
        MysqlConn.ConnectionString = "server=localhost; userid=root; password=root; database=isp_database"
        MysqlConn.Open()

        Dim Query As String = "SELECT COUNT(*) FROM isp_database.bill_table"
        Command = New MySqlCommand(Query, MysqlConn)

        Dim dt As New DataTable
        dt.Clear()
        Using da As New MySqlDataAdapter(Command)
            da.Fill(dt)
        End Using

        Dim currentRowCount As Integer = dt.Rows(0)(0)

        If currentRowCount > previousRowCount Then
            previousRowCount = currentRowCount
            Return True
        End If

        Return False
        MysqlConn.Close()
    End Function

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        date_txt.Text = Date.Now.ToString("MM-dd-yyyy hh:mm:ss")
        ' Check if new data has been inserted
        If CheckForNewData() Then
            UpdateStatusToUnpaid()
            UpdateDateDue()
        End If

        CheckUnpaidCustomers()

        StoreBillingDetailsToMonthlyTable()

        ' Reset the timer
        timer.Stop()
        timer.Start()
    End Sub


    Public Sub CheckUnpaidCustomers()
        Dim MysqlConn1 As MySqlConnection = New MySqlConnection()
        Dim MysqlConn2 As MySqlConnection = New MySqlConnection()
        Dim selectCommand As MySqlCommand
        Dim updateCommand As MySqlCommand
        Dim READER As MySqlDataReader

        MysqlConn1.ConnectionString = "server=localhost; userid=root; password=root; database=isp_database; "
        MysqlConn2.ConnectionString = "server=localhost; userid=root; password=root; database=isp_database; "

        ' Get current date
        Dim currentDate As DateTime = DateTime.Now

        ' Calculate due date as 28th day of the current month
        Dim dueDate As DateTime = New DateTime(currentDate.Year, currentDate.Month, 28)

        MysqlConn1.Open()
        MysqlConn2.Open()

        ' Create SQL SELECT statement
        Dim selectQuery As String = "SELECT client_id, amount, date_due FROM isp_database.bill_table WHERE status = 'UNPAID'"

        ' Create command object
        selectCommand = New MySqlCommand(selectQuery, MysqlConn1)
        selectCommand.Parameters.AddWithValue("@date_due", dueDate)

        ' Execute the SELECT statement
        READER = selectCommand.ExecuteReader()

        ' Iterate through the records
        While READER.Read()
            Dim cid As Integer = READER("client_id")

            Dim amount As Decimal = 0 ' Initialize amount to a default value

            If Not Convert.IsDBNull(READER("amount")) Then
                amount = Convert.ToDecimal(READER("amount"))
            End If

            ' Calculate penalty amount
            Dim penaltyAmount As Decimal = amount * 0.2


            ' Create SQL UPDATE statement without due date
            Dim updateQuery As String = "UPDATE isp_database.bill_table SET status = 'UNPAID', penalty = @penalty WHERE client_id = @client_id"

            ' Create command object
            updateCommand = New MySqlCommand(updateQuery, MysqlConn2)
            updateCommand.Parameters.AddWithValue("@penalty", penaltyAmount)
            updateCommand.Parameters.AddWithValue("@client_id", cid)

            ' Execute the UPDATE statement
            updateCommand.ExecuteNonQuery()
        End While

        ' Close the reader and the database connections
        READER.Close()
        MysqlConn1.Close()
        MysqlConn2.Close()
    End Sub

    Private Sub UpdateStatusToUnpaid()
        Dim Conn1 As MySqlConnection = New MySqlConnection()
        Conn1.ConnectionString = "server=localhost; userid=root; password=root; database=isp_database; "
        Conn1.Open()
        Dim READER As MySqlDataReader
        Dim Query As String
        Query = "UPDATE isp_database.bill_table SET Status = 'UNPAID' where date=NULL"
        Command = New MySqlCommand(Query, Conn1)
        READER = Command.ExecuteReader()
        READER.Close()
        Conn1.Close()
    End Sub

    Private Sub UpdateDateDue()
        Dim Conn2 As MySqlConnection = New MySqlConnection()
        Conn2.ConnectionString = "server=localhost; userid=root; password=root; database=isp_database; "
        Conn2.Open()
        Dim READER As MySqlDataReader
        Dim currentDate As DateTime = DateTime.Now
        Dim dueDate As DateTime = New DateTime(currentDate.Year, currentDate.Month, 28)
        Dim due As String = dueDate.ToString("yyyy-MM-dd") ' Convert to yyyy-MM-dd format
        Dim Query As String
        Query = "UPDATE isp_database.bill_table SET date_due = '" & due & "'"
        Command = New MySqlCommand(Query, Conn2)
        READER = Command.ExecuteReader()
        Conn2.Close()
    End Sub

    Public Sub StoreBillingDetailsToMonthlyTable()
        Dim Conn1 As MySqlConnection = New MySqlConnection()
        Conn1.ConnectionString = "server=localhost; userid=root; password=root; database=isp_database;"

        ' Open the connection
        Conn1.Open()

        ' Retrieve billing details from the bill table
        Dim selectQuery As String = "SELECT * FROM isp_database.bill_table"
        Dim selectCommand As MySqlCommand = New MySqlCommand(selectQuery, Conn1)
        Dim reader As MySqlDataReader = selectCommand.ExecuteReader()

        ' Get the current month and year
        Dim currentDate As DateTime = DateTime.Now
        Dim currentMonth As Integer = currentDate.Month
        Dim monthName As String = currentDate.ToString("MMMM")
        Dim currentYear As Integer = currentDate.Year

        ' Iterate through the billing details
        While reader.Read()

            Dim client_id As Integer = CInt(reader("client_id"))
            Dim bill_no As Integer = CInt(reader("bill_id"))
            Dim amount_paid As Decimal = If(reader.IsDBNull(reader.GetOrdinal("amount")), 0, CDec(reader("amount")))

            If reader.IsDBNull(reader.GetOrdinal("date")) Then
                ' Handle DBNull case
                Dim date_paid As DateTime = DateTime.MinValue ' or any default value you prefer
            Else
                ' Convert the 'date' value to DateTime
                Dim date_paid As DateTime = CDate(reader("date"))


                ' Get the month and year from the billing date
                Dim billingMonth As Integer = date_paid.Month
                Dim billingYear As Integer = date_paid.Year

                ' Check if the billing date is in the current month and year
                If billingMonth = currentMonth AndAlso billingYear = currentYear Then
                    ' Insert billing details into the monthly table
                    Dim insertQuery As String = "INSERT INTO isp_database.monthly_table (month_name, bill_no, client_id, amount_paid, date_paid) VALUES (@bill_no, @client_id, @amount_paid, @date_paid)"
                    Dim insertCommand As MySqlCommand = New MySqlCommand(insertQuery, Conn1)

                    ' Add parameters to the insert command
                    insertCommand.Parameters.Add("@month_name", SqlDbType.NVarChar).Value = monthName
                    insertCommand.Parameters.Add("@bill_no", SqlDbType.Int).Value = bill_no
                    insertCommand.Parameters.Add("@client_id", SqlDbType.Int).Value = client_id
                    insertCommand.Parameters.Add("@amount_paid", SqlDbType.Decimal).Value = amount_paid
                    insertCommand.Parameters.Add("@date_paid", SqlDbType.Date).Value = date_paid

                    ' Execute the insert command
                    insertCommand.ExecuteNonQuery()

                End If
            End If
        End While

        ' Close the reader and connection
        reader.Close()
        Conn1.Close()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles paid_btn.Click
        MysqlConn = New MySqlConnection()
        MysqlConn.ConnectionString = "server=localhost; userid=root; password=root; database=isp_database"
        Dim READER As MySqlDataReader

        Try
            MysqlConn.Open()

            Dim inDate As DateTime = DateTimePicker1.Value ' Get selected date from DateTimePicker
            Dim inDateStr As String = inDate.ToString("yyyy-MM-dd") ' Convert to yyyy-MM-dd format
            Dim Query As String

            Query = "update isp_database.bill_table set status= 'PAID', connection='CONNECTED', penalty=NULL, date= '" & inDateStr & "' where client_id= '" & cid_tb.Text & "'"
            Command = New MySqlCommand(Query, MysqlConn)
            READER = Command.ExecuteReader
            Dim cid As String = cid_tb.Text.ToString()
            MessageBox.Show("CUSTOMER " & cid & " PAID!")



            MysqlConn.Close()

            Display_Table()

        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
            cid_tb.Text = ""
            name_tb.Text = ""
            plan_tb.Text = ""
            price_tb.Text = ""

        End Try
    End Sub

    Public Sub Display_Table()
        Try
            Dim Str As String
            Str = "select * from isp_database.bill_table"
            MysqlConn.Open()
            Dim da As New MySqlDataAdapter(Str, MysqlConn)
            Dim ds As DataSet = New DataSet
            Dim dt As New DataTable
            dt.Clear()
            da.Fill(dt)
            DataGridView1.DataSource = dt
            MysqlConn.Close()


        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
MySQL vb.net

评论

0赞 nbk 5/1/2023
为什么要混用参数和字符串串联的SQL语句,只使用带参数的语句,还要Make AINSERt INTO monthly_table SELECT ...FROM bill_table WHERE date = curren_month
0赞 Andrew Morton 5/1/2023
顺便说一句:1) 每个 SQL 连接对象都需要在使用完后作为 sooon 进行处理,因此在 Try...捕获语句并放入其中。2) 最好将该行作为 tick 事件处理程序的第一行,这样如果里面的代码需要一段时间,就不会引发另一个 tick 事件。FinallyMysqlConn.Dispose()timer.Stop()
0赞 Ben the Coder 5/1/2023
请修剪您的代码,以便更轻松地找到您的问题。请遵循这些准则,以创建最小的可重现示例
0赞 Craig 5/1/2023
您是否尝试过在调试器中运行它、设置断点并单步执行代码?这可能有助于您找到行为不符合您期望的地方。
0赞 jmcilhinney 5/1/2023
你以错误的方式看待这个问题,这使得解决问题变得更加困难。不要只是把泥巴扔到墙上,希望有什么东西粘住。首先是逻辑,然后是代码。您应该首先问问自己,您希望在何时或在什么情况下执行代码。一旦您知道应用中发生的情况应该触发代码的执行,您就可以找出在这些情况下引发的事件。到目前为止,你已经使用的事实和事件表明你没有把这种想法放在其中。LoadTickClick

答: 暂无答案