所以我是这个网站的第一次海报,长期用户。无论何时我有问题,我都要确保先来这里。无论如何,我正在尝试使用VB中的现有MySQL数据库和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
如果有人可以再次提供帮助,我将非常感激。
答案 0 :(得分: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
通过这种方式,在异常情况下不再需要连接,命令和适配器时,请立即关闭并处理它们。 See Using Statement