在VB.Net中自动更新数据库

时间:2017-07-14 03:00:31

标签: vb.net

我希望每次插入数据时都会在我的数据库上进行自动刷新或更新,但它会继续复制我的数据库,您需要手动点击刷新按钮才能看到更新的表格。

以下是我的代码:

Imports MySql.Data.MySqlClient


Public Class Form2

    Dim MysqlConn As MySqlConnection
    Dim Command As MySqlCommand
    Dim dbDataSet As New DataTable

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogout.Click
        Form1.Show()
        Me.Hide()
    End Sub

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

        Try
            MysqlConn.Open()
            Dim Query As String
            Query = "Insert into databse.employeeinfo (idEmployeeInfo,name,surname,age) values ('" & tbEID.Text & "', '" & tbUname.Text & "', '" & tbPassword.Text & "', '" & tbAge.Text & "')"
            Command = New MySqlCommand(Query, MysqlConn)
            READER = Command.ExecuteReader

            MessageBox.Show("Data Save")

            MysqlConn.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            MysqlConn.Dispose()
        End Try
        Load_Form()

    End Sub

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

        Try
            MysqlConn.Open()
            Dim Query As String
            Query = "Update databse.employeeinfo set idEmployeeInfo = '" & tbEID.Text & "', name = '" & tbUname.Text & "', surname = '" & tbPassword.Text & "', age = '" & tbAge.Text & "' where idEmployeeInfo = '" & tbEID.Text & "' "
            Command = New MySqlCommand(Query, MysqlConn)
            READER = Command.ExecuteReader

            MessageBox.Show("Data Updated")

            MysqlConn.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            MysqlConn.Dispose()
        End Try

    End Sub

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

        Try
            MysqlConn.Open()
            Dim Query As String
            Query = "Delete from databse.employeeinfo where idEmployeeInfo = '" & tbEID.Text & "' "
            Command = New MySqlCommand(Query, MysqlConn)
            READER = Command.ExecuteReader

            MessageBox.Show("Data Deleted")

            MysqlConn.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            MysqlConn.Dispose()
        End Try

    End Sub

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Load_Form()
        MysqlConn = New MySqlConnection
        MysqlConn.ConnectionString = "server=localhost;userid=root;password=Password;database=databse"
        Dim READER As MySqlDataReader

        Try
            MysqlConn.Open()
            Dim Query As String
            Query = "Select * from databse.employeeInfo"
            Command = New MySqlCommand(Query, MysqlConn)
            READER = Command.ExecuteReader

            While READER.Read
                Dim sName = READER.GetString("name")
                ComboBox1.Items.Add(sName)
                ListBox1.Items.Add(sName)
            End While

            MysqlConn.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            MysqlConn.Dispose()
        End Try
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        MysqlConn = New MySqlConnection
        MysqlConn.ConnectionString = "server=localhost;userid=root;password=Password;database=databse"
        Dim READER As MySqlDataReader

        Try
            MysqlConn.Open()
            Dim Query As String
            Query = "Select * from databse.employeeInfo where name= '" & ComboBox1.Text & "'"
            Command = New MySqlCommand(Query, MysqlConn)
            READER = Command.ExecuteReader

            While READER.Read
                tbEID.Text = READER.GetInt32("idEmployeeInfo")
                tbUname.Text = READER.GetString("name")
                tbPassword.Text = READER.GetString("surname")
                tbAge.Text = READER.GetInt32("age")
            End While

            MysqlConn.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            MysqlConn.Dispose()
        End Try
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        MysqlConn = New MySqlConnection
        MysqlConn.ConnectionString = "server=localhost;userid=root;password=Password;database=databse"
        Dim READER As MySqlDataReader

        Try
            MysqlConn.Open()
            Dim Query As String
            Query = "Select * from databse.employeeInfo where name= '" & ListBox1.Text & "'"
            Command = New MySqlCommand(Query, MysqlConn)
            READER = Command.ExecuteReader

            While READER.Read
                tbEID.Text = READER.GetInt32("idEmployeeInfo")
                tbUname.Text = READER.GetString("name")
                tbPassword.Text = READER.GetString("surname")
                tbAge.Text = READER.GetInt32("age")
            End While

            MysqlConn.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            MysqlConn.Dispose()
        End Try
    End Sub
    Private Sub Load_Form()
        MysqlConn = New MySqlConnection
        MysqlConn.ConnectionString = "server=localhost;userid=root;password=Password;database=databse"
        Dim SDA As New MySqlDataAdapter

        Dim bSource As New BindingSource


        Try
            MysqlConn.Open()
            Dim Query As String
            Query = "Select * from databse.employeeInfo"
            Command = New MySqlCommand(Query, MysqlConn)


            SDA.SelectCommand = Command
            SDA.Fill(dbDataSet)
            bSource.DataSource = dbDataSet
            DataGridView1.DataSource = bSource
            SDA.Update(dbDataSet)

            MysqlConn.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            MysqlConn.Dispose()
        End Try
    End Sub

    Private Sub btnLOADdb_Click(sender As Object, e As EventArgs) Handles btnLOADdb.Click
        MysqlConn = New MySqlConnection
        MysqlConn.ConnectionString = "server=localhost;userid=root;password=Password;database=databse"
        Dim SDA As New MySqlDataAdapter
        Dim dbDataSet As New DataTable
        Dim bSource As New BindingSource


        Try
            MysqlConn.Open()
            Dim Query As String
            Query = "Select * from databse.employeeInfo"
            Command = New MySqlCommand(Query, MysqlConn)


            SDA.SelectCommand = Command
            SDA.Fill(dbDataSet)
            bSource.DataSource = dbDataSet
            DataGridView1.DataSource = bSource
            SDA.Update(dbDataSet)

            MysqlConn.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            MysqlConn.Dispose()
        End Try

    End Sub

    Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        If e.RowIndex >= 0 Then
            Dim Row As DataGridViewRow
            Row = Me.DataGridView1.Rows(e.RowIndex)

            tbEID.Text = Row.Cells("idEmployeeInfo").Value.ToString
            tbUname.Text = Row.Cells("name").Value.ToString
            tbPassword.Text = Row.Cells("surname").Value.ToString
            tbAge.Text = Row.Cells("age").Value.ToString

        End If
    End Sub

    Private Sub tbSearch_TextChanged(sender As Object, e As EventArgs) Handles tbSearch.TextChanged
        Dim DV As New DataView(dbDataSet)
        DV.RowFilter = String.Format("name Like '%{0}%'", tbSearch.Text)
        DataGridView1.DataSource = DV

    End Sub
End Class

感谢。

1 个答案:

答案 0 :(得分:0)

每次调用更新或删除数据库中的记录后,您需要执行将更新表单中结果的代码。

因此,在btnDelete_ClickbtnUpdate_Click结束时,您需要以Load_Form()

中的相同方式致电Button1_Click_1

除此之外,还有一些提示。

从不将原始数据发送到SQL查询,或者您正在向应用程序开放攻击。例如。如果某人将Pwnd'; Drop Table employeeinfo; --输入tbUname.Text您的员工信息表中,将被删除。

相反,始终在参数化查询中将用户输入作为参数发送。

数据适配器很有用,但速度很慢。构建自己的数据表会更快。

利用重用代码的能力并为数据访问创建一个类,这样您就不需要编写代码来处理打开连接,初始化命令以及每次需要数据时处理错误:

Public Class MySqlHelper
    Public Shared Function GetConnection() As MySqlConnection
        Return New MySqlConnection("server=localhost;userid=root;password=Password;database=databse")
    End Function
    Public Shared Function ExecuteReader(Query As String) As MySqlDataReader
        Dim conn As MySqlConnection = GetConnection()
        Dim dr As MySqlDataReader
        Try
            conn.Open()
            Dim Command As New MySqlCommand(Query, conn)
            dr = Command.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
            Return dr
        Catch ex As Exception
            conn.Close()
            conn.Dispose()
            conn = Nothing
            Throw
        End Try
    End Function
    Public Shared Function ExecuteReader(Query As String, ByVal Params() As String, ByVal Values() As Object) As MySqlDataReader
        If Params Is Nothing OrElse Values Is Nothing OrElse Params.Length = 0 OrElse Params.Length <> Values.Length Then
            Throw New ArgumentException()
        End If
        Dim conn As MySqlConnection = GetConnection()
        Dim dr As MySqlDataReader
        Try
            conn.Open()
            Dim Command As New MySqlCommand(Query, conn)
            For I As Integer = 0 To Params.Length - 1
                Command.Parameters.AddWithValue(Params(I), Values(I))
            Next
            dr = Command.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
            Return dr
        Catch ex As Exception
            conn.Close()
            Throw
        End Try
    End Function

    Public Shared Function ExecuteScalar(Query As String) As Object
        Dim dr As MySqlDataReader = ExecuteReader(Query)
        Dim result As Object = Nothing
        If dr.Read Then
            result = dr(0)
        End If
        dr.Close()
        Return result
    End Function
    Public Shared Function ExecuteScalar(Query As String, ByVal Params() As String, ByVal Values() As Object) As Object
        Dim dr As MySqlDataReader = ExecuteReader(Query, Params, Values)
        Dim result As Object = Nothing
        If dr.Read Then
            result = dr(0)
        End If
        dr.Close()
        Return result
    End Function

    Public Shared Function GetDataTable(Query As String) As DataTable
        Dim dt As DataTable = New DataTable
        Try

            Dim dr As MySqlDataReader = ExecuteReader(Query)
            If dr.Read Then

                For i As Integer = 0 To dr.FieldCount - 1
                    dt.Columns.Add(dr.GetName(i))
                Next
                Dim row As DataRow = dt.NewRow
                For i As Integer = 0 To dr.FieldCount - 1
                    row(i) = dr(i)
                Next
                dt.Rows.Add(row)
                While dr.Read
                    row = dt.NewRow
                    For i As Integer = 0 To dr.FieldCount - 1
                        row(i) = dr(i)
                    Next
                    dt.Rows.Add(row)
                End While
            End If
            dr.Close()
            Return dt

        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
            Throw
        End Try

    End Function

End Class

正如您所看到的,Class具有允许您发送参数名称和值数组的重载。然后使用'Command.AddWithValue`将它们添加到您的命令中,这样您的命令就不会受到Sql Injection攻击的影响。

您可以在需要数据库访问时甚至在其他项目中重用该类。使用类代码可以像这样重写:

Public Class Form2
    Inherits Form
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogout.Click
        Form1.Show()
        Me.Hide()
    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Query As String = "Insert into databse.employeeinfo (idEmployeeInfo,name,surname,age) values (@EID,@Uname,@Pwd,@Age)"
        Try
            MySqlHelper.ExecuteScalar(Query, {"@Eid", "@Uname", "@Pwd", "@Age"}, {tbEID.Text, tbUname.Text, tbPassword.Text, tbAge.Text})
            MessageBox.Show("Data Saved")
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Load_Form()


    End Sub

    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
        Dim Query As String = "Update databse.employeeinfo setname=@uname,surname=@surname,age=@age where idEmployeeInfo=@eid"
        Try
            MySqlHelper.ExecuteScalar(Query, {"@Eid", "@Uname", "@Pwd", "@Age"}, {tbEID.Text, tbUname.Text, tbPassword.Text, tbAge.Text})
            MessageBox.Show("Data Saved")
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Load_Form()

    End Sub

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        Dim Query As String = "Delete from databse.employeeinfo where idEmployeeInfo=@eid"
        Try
            MySqlHelper.ExecuteScalar(Query, {"@Eid"}, {tbEID.Text})
            MessageBox.Show("Data Deleted")
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)


        End Try
        Load_Form()
    End Sub

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Try
            Dim Query = "Select * from databse.employeeInfo"
            Dim dr As MySqlDataReader = MySqlHelper.ExecuteReader(Query)
            While dr.Read
                Dim sName = dr.GetString("name")
                ComboBox1.Items.Add(sName)
                ListBox1.Items.Add(sName)
            End While
            dr.Close()
        Catch ex As MySqlException

            MessageBox.Show(ex.Message)
        End Try

        Load_Form()
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        Try

            Dim Query As String = "Select * from databse.employeeInfo where name=@Name"
            Dim dr As MySqlDataReader = MySqlHelper.ExecuteReader(Query, {"@name"}, {ComboBox1.Text})
            If dr.Read Then ' no need for while since we are only reading single record
                tbEID.Text = dr.GetInt32("idEmployeeInfo")
                tbUname.Text = dr.GetString("name")
                tbPassword.Text = dr.GetString("surname")
                tbAge.Text = dr.GetInt32("age")
            End If
            dr.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        Try
            Dim Query As String = "Select * from databse.employeeInfo where name=@Name"

            Dim dr As MySqlDataReader = MySqlHelper.ExecuteReader(Query, {"@name"}, {ListBox1.Text})

            If dr.Read Then ' no need for while since we are only reading single record
                tbEID.Text = dr.GetInt32("idEmployeeInfo")
                tbUname.Text = dr.GetString("name")
                tbPassword.Text = dr.GetString("surname")
                tbAge.Text = dr.GetInt32("age")
            End If


        Catch ex As MySqlException
            MessageBox.Show(ex.Message)

        End Try
    End Sub

    Public DbDataSet As DataTable
    Private Sub Load_Form()

        Dim bSource As New BindingSource
        Try
            Dim Query As String = "Select * from databse.employeeInfo"
            DbDataSet = MySqlHelper.GetDataTable(Query)
            bSource.DataSource = DbDataSet
            DataGridView1.DataSource = bSource

        Catch ex As MySqlException
            MessageBox.Show(ex.Message)

        End Try
    End Sub

    Private Sub btnLOADdb_Click(sender As Object, e As EventArgs) Handles btnLOADdb.Click

        Dim bSource As New BindingSource
        Try
            Dim Query As String = "Select * from databse.employeeInfo"
            DbDataSet = MySqlHelper.GetDataTable(Query)
            bSource.DataSource = DbDataSet
            DataGridView1.DataSource = bSource

        Catch ex As MySqlException
            MessageBox.Show(ex.Message)

        End Try

    End Sub

    Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        If e.RowIndex >= 0 Then
            Dim Row As DataGridViewRow
            Row = Me.DataGridView1.Rows(e.RowIndex)

            tbEID.Text = Row.Cells("idEmployeeInfo").Value.ToString
            tbUname.Text = Row.Cells("name").Value.ToString
            tbPassword.Text = Row.Cells("surname").Value.ToString
            tbAge.Text = Row.Cells("age").Value.ToString

        End If
    End Sub

    Private Sub tbSearch_TextChanged(sender As Object, e As EventArgs) Handles tbSearch.TextChanged
        Dim DV As New DataView(dbDataSet)
        DV.RowFilter = String.Format("name Like '%{0}%'", tbSearch.Text)
        DataGridView1.DataSource = DV

    End Sub
End Class