1

所以我是第一次发帖,是这个网站的长期用户。每当我有问题时,我总是确保先来这里。无论如何,我正在尝试使用现有的 MySQL 数据库和 VB 中的 Visual Studio 2010 构建一个 CRM 应用程序。这是我到目前为止的代码,我正在尝试将 mysql 查询的结果返回到列表视图中,然后当有人双击一行时,它会打开该帐户。这是我到目前为止的代码。

我已经为此工作了几个小时,如果有人可以帮助我,我将不胜感激。我是 VB 的一个极端菜鸟,但对 MYSQL 来说还不错。

Imports MySql.Data.MySqlClient
Public Class mainWindow
Public sConnection As New MySqlConnection
Private Sub mainWindow_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If sConnection.State = ConnectionState.Closed Then
        sConnection.ConnectionString = "SERVER = localhost; USERID = system; PASSWORD =; DATABASE = system"
        sConnection.Open()
    End If
End Sub

Private Sub searchBtn_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles searchBtn.Click, Button1.Click
    Dim sqlQuery As String = "Select * from tblclients"
    Dim sqlAdapter As MySqlDataAdapter
    Dim sqlCommand As New MySqlCommand
    Dim Table As New DataTable
    Dim i As Integer

    With sqlCommand
        .CommandText = sqlQuery
        .Connection = sConnection

    End With

    With sqlAdapter
        .SelectCommand = sqlCommand
        .Fill(Table)
    End With
    For i = 0 To Table.Rows.Count - 1
        With dataView
            .Items.Add(Table.Rows(i)("id"))
            With .Items(.Items.Count - 1).SubItems
                .Add(Table.Rows(i)("fname"))
                .Add(Table.Rows(i)("lname"))
                .Add(Table.Rows(i)("company"))
                .Add(Table.Rows(i)("email"))
                .Add(Table.Rows(i)("phone"))
                .Add(Table.Rows(i)("state"))
                .Add(Table.Rows(i)("zipcode"))
            End With
        End With
    Next
End Sub
End Class

如果有人可以再次提供帮助,我将不胜感激。

4

1 回答 1

0

缺少 MySqlDataAdapter 上的新功能

Dim sqlAdapter As New MySqlDataAdapter

这将解决您的问题Object reference not set.....,但是,实际上您应该遵循 Tim Schmelter 的建议。永远不要在表单/应用程序的整个生命周期内保持全局连接。这将是一场等待发生的灾难(尤其是对于似乎对泄漏连接更敏感的 MySql)

Private Sub searchBtn_Click_1(.....) Handles searchBtn.Click, Button1.Click

    Using sConnection = new MySqlConnection(.......)
    Using sqlCommand = new MySqlCommand("Select * from tblclients", sConnection)
        sConnection.Open()
        Using sqlAdapter As New MySqlDataAdapter()
            Dim Table As New DataTable
            Dim i As Integer
            With sqlAdapter
                .SelectCommand = sqlCommand
                .Fill(Table)
            End With
        ...... ' the rest of your code that fills the view'
        End Using
    End Using
    End Using
End Sub

通过这种方式,您关闭并处理连接、命令和适配器在它们不再需要之后立即处理异常情况。请参阅使用语句

于 2013-08-15T22:31:33.020 回答