vb.net - 在多个表单之间共享 mdb 访问连接 [英] vb.net - sharing mdb access connection among multiple forms
问题描述
我开始将数据库放入我的应用程序中,但是我对如何在我的 MDI 应用程序中的十几种不同形式之间共享数据库连接一无所知.我假设这与接口或其他东西有关,但我在任何地方都找不到任何相关示例.有人可以帮我吗?理想情况下,我想要的是当应用程序加载时,会调用表单加载区域中的一个函数,该函数建立到 mdb 的单个连接,然后我可以通过任何表单调用它,所以我不必总是每次我需要更新数据库时打开/关闭连接(假设我的建议对开销更好),除非这是一个更好的选择?
I'm starting to put in a database into my application, however I'm drawing a blank on how to share a database connection among the dozen or so different forms in my MDI application. I'm assuming this has to do with interfaces or something but I can't find any relevant examples anywhere. Can someone help me out? Ideally what I'd like is when the app is loaded up there is a call to a function in the forms loading area which establishes a single connection to the mdb, that I can then call via any form so I don't always have to open/close connections everytime I need to update the db (assuming what I'm suggesting is better for overhead), unless that is a better option?
这是我使用的 mdb 数据库访问代码的基本示例:
Here's a basic example of the mdb database access code I've got working:
Dim dt As DataTable = New DataTable()
Dim OleDbTran As OleDbTransaction = Nothing
Using connJET As OleDbConnection = New OleDbConnection("connection string here...")
Try
connJET.Open()
Dim sqlCount As OleDbCommand = New OleDbCommand("select * from mytable", connJET)
Using aReader As OleDbDataReader = sqlCount.ExecuteReader()
dt.Load(aReader)
End Using
If (dt.Rows.Count > 0) Then
MsgBox(dt.Rows.Count)
End If
OleDbTran = connJET.BeginTransaction()
Dim aCommand As OleDbCommand = connJET.CreateCommand()
aCommand.CommandText = "INSERT INTO Programs (title) VALUES (@title)"
aCommand.Transaction = OleDbTran
aCommand.Parameters.Add("@title", OleDbType.VarChar)
aCommand.Parameters("@title").Value = "Test"
aCommand.ExecuteNonQuery()
OleDbTran.Commit()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
推荐答案
假设您在启动表单中创建了连接,那么您只需将构造函数添加到其他接受 SqlConnection 的表单中,并在您创建一个时发送它该表单的实例.
Assuming that you create the connection in your startup form, then you could just add constructors to the other forms that accept a SqlConnection and send that in whenever you create an instance of that form.
或者,如果您愿意,您可以创建如下内容:
Or if you prefer, you create something like this:
Public Class Connection
Private Shared connection As OleDb.OleDbConnection
Public Shared ReadOnly Property Instance As OleDb.OleDbConnection
Get
If connection Is Nothing Then
connection = New OleDb.OleDbConnection("connstring")
End If
Return connection
End Get
End Property
End Class
然后您可以在需要时调用 Connection.Instance
来访问它.
And then you could access it by just calling Connection.Instance
whenever you need it.
这篇关于vb.net - 在多个表单之间共享 mdb 访问连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!