VB.NET 操作Access数据库增删改数据

    科技2025-10-01  27

    Imports System.Data.OleDb

     Public cn As New OleDb.OleDbConnection, my_cmd As New OleDbCommand, sql_cmd As String, my_dr As OleDbDataReader     Public da As OleDbDataAdapter     Public ds As DataSet     '******************************************     '函数名称:sql_cmd     '作者:黄小龙     '创建日期:2013-11-5     '形参:Comm_sql 字符 ,sql命令     '返回值:0 异常 1成功     '功能:执行数据增 删 改 指令!     Function access_cmd(ByVal Comm_sql As String) As Integer         Try             If cn.State = 1 Then             Else                 cn.Open()             End If             my_cmd = New OleDbCommand             my_cmd.Connection = cn             my_cmd.CommandText = Comm_sql             my_cmd.ExecuteNonQuery()             access_cmd = 1         Catch ex As Exception             access_cmd = 0             MsgBox(ErrorToString)         End Try     End Function     '******************************************     '函数名称:sql_connect     '作者:黄小龙     '创建日期:2016-07-15     '形参:无     '返回值:0 异常 1成功     '功能:连接数据库     Function sql_connect()         Try             If cn.State = 1 Then             Else                 If (System.Runtime.InteropServices.Marshal.SizeOf(IntPtr.Zero) = 4) Then '判断系统位数 4是32位系统 8是64位系统                     cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\long.mdb;Jet OLEDB:Database Password=*******"                 Else                     cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\long.mdb;Jet OLEDB:Database Password=*******"                 End If                 cn.Open()             End If             sql_connect = 1         Catch ex As Exception             MsgBox("数据库连接异常:" + Err.Description)             sql_connect = 0         End Try     End Function

    '更新数据库表内容使用示例   

    Private Sub Button7_Click_1(sender As Object, e As EventArgs) Handles Button7.Click         Dim sg_index2 As Integer() = {0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1} '2020年排序表         sg_index = sg_index2         '随年限自动变更生肖算法         Dim kk = Now.Year - 2020         For i = 1 To kk             For u = 0 To 10                 sg_index(u) = sg_index2(u + 1)             Next             sg_index(11) = sg_index2(0)         Next         Dim cmd_string As String, cmd_string2 As String, result As Integer         cmd_string = "update  sx_index set sx1=" + sg_index(0).ToString         cmd_string2 = ""         For i = 1 To 11             cmd_string2 = cmd_string2 + ",sx" + (i + 1).ToString + "=" + sg_index(i).ToString         Next         cmd_string = cmd_string + cmd_string2

            sql_connect()'连接数据库         result = access_cmd(cmd_string)         If result = 1 Then             MsgBox("生肖更新成功,软件重启后生效!")         Else             MsgBox("保存失败!" + Err.Description)         End If     End Sub

    Processed: 0.020, SQL: 8