VS2013 对Access数据库 进行增删改查, 求大神帮帮忙,很急的

2024-10-30 11:22:35
有1个网友回答
网友(1):

见下面的代码,自己换成真实的数据库及表即可

Imports System.Data
Imports System.IO
Imports System.Data.OleDb
Module Module1
Public cn1 As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ACCESS数据库1.mdb") '定义连接1---这里请更改为实际数据库路径及名称
Public cn2 As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data 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