有密码:
string connectionString =@"Provider=Microsoft.Jet.OLEDB.4.0Data Source=你存放access数据库文件的地址,即 文件路径\文件名.mdb "Persist Security Info=TrueJet OLEDB:Database Password=1234"
没有密码:
string connectionString =@"Provider=Microsoft.Jet.OLEDB.4.0Data Source=你存放access数据库文件的地址,即 文件路径\文件名.mdb "Persist Security Info=True"
其他oledb和sql连接数据库所用的方法都是一样的,只需要将Sql改为oleDb即可。
见下面的代码,自己换成真实的数据库及表即可Imports System.Data
Imports System.IO
Imports System.Data.OleDb
Module Module1
Public cn1 As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0Data Source=C:\ACCESS数据库1.mdb") '定义连接1---这里请更改为实际数据库路径及名称
Public cn2 As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0Data Source=C:\ACCESS数据库2.mdb") '定义连接2---这里请更改为实际数据库路径及名称
Public DataBaseRST1 As Integer '用来返回数据库执行结果
Public DataBaseRST2 As Integer '用来返回数据库执行结果
Public Function DataModify(ByVal str_cmd1 As String, ByVal str_cmd2 As String) As Boolean '进行数据库修改 *** 作函数
Dim cmdinsert1 As New OleDbCommand
Dim cmdinsert2 As New OleDbCommand
Try
cmdinsert1.CommandText = str_cmd1
cmdinsert2.CommandText = str_cmd2
cmdinsert1.Connection = cn1
cmdinsert2.Connection = cn2
If cn1.State = ConnectionState.Closed Then cn1.Open()
If cn2.State = ConnectionState.Closed Then cn2.Open()
DataBaseRST1 = cmdinsert1.ExecuteNonQuery() '用来返回执行的结果
DataBaseRST2 = cmdinsert2.ExecuteNonQuery() '用来返回执行的结果
cn1.Close()
cn2.Close()
Return True
Catch ex As Exception
MessageBox.Show(Err.Description, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return False
End Try
End Function
End Module
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DataModify("insert into aa values ('1','2')", "insert into aa values ('1','2')") '调用方法
End Sub
End Class
追问
这个方法我只能用于添加修改删除,请问,查询数据并且绑定到DGV怎么做?
回答
Public Function Search(ByVal cn1 As OleDb.OleDbConnection, ByVal cn2 As OleDb.OleDbConnection, ByVal str_cmd1 As String, ByVal str_cmd2 As String, ByVal DGV1 As DataGridView, ByVal DGV2 As DataGridView) As Boolean '查询 str_cmd1,str_cmd2---查询命令,DGV1,DGV2---DataGridView,用来显示数据的控件
Dim tb1 As New DataTable
Dim tb2 As New DataTable
Try
Dim ap1 As New OleDb.OleDbDataAdapter(str_cmd1, cn1)
ap1.Fill(tb1)
DGV1.DataSource = tb1
Dim ap2 As New OleDb.OleDbDataAdapter(str_cmd2, cn2)
ap2.Fill(tb2)
DGV2.DataSource = tb2
Return True
Catch ex As Exception
MessageBox.Show(Err.Description, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return False
End Try
视图->服务器资源管理器->数据连接->添加连接->选择新数据源在"选择数据源"里选第一个microsoft access 数据库文件--点"继续"--d出"添加连接"对话框 然后添加你要连接的数据库服务连接
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)