[英]vb.net - sharing mdb access connection among multiple forms
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. 我开始将数据库放入我的应用程序中,但是在如何在MDI应用程序中的十几种不同形式之间共享数据库连接方面,我还是处于空白。 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: 这是我正在工作的mdb数据库访问代码的基本示例:
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
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. 假设您在启动表单中创建了连接,则只需将构造函数添加到接受SqlConnection的其他表单中,并在每次创建该表单的实例时将其发送给该表单。
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
And then you could access it by just calling Connection.Instance
whenever you need it. 然后您可以通过在需要时仅调用Connection.Instance
来访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.