代码之家  ›  专栏  ›  技术社区  ›  Pradip Dhakal

无法更新当前锁定的vb。净误差

  •  0
  • Pradip Dhakal  · 技术社区  · 6 年前

    我想在2个不同的 table of ms-access

    它显示了这个错误。

    enter image description here

    我有这样一个代码:

    try
     dim sql1,sql2 as string
     sql1 = "INSERT INTO table1(something)VALUES(something)"
     cmd = new oledbcommand(sql1, connection)
     cmd.executenoquery()
    
     sql2 = "INSERT INTO table2(something)VALUES(something)"
     cmd2 = new oledbcommand(sql2, connection)
     cmd2.executenoquery()
    catch ex as exception
      msgbox(ex.tostring())
    
    (where these cmd1,cmd2 are defined in controlModule.)
    

    那么,我该怎么办?

    非常感谢您的帮助。非常感谢。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Tim Schmelter    6 年前

    我认为关闭连接可以解决问题,最好使用 Using -声明:

    try
        Using con As OleDbConnection = GetConnection() ' or New OlebConnection(...)
            Using cmd = con.CreateCommand()
                cmd.CommandText = "INSERT INTO table1(something)VALUES(@something)"
                cmd.Parameters.AddWithValue("@something", something)
                con.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Using 
    
        Using con As OleDbConnection = GetConnection()
            Using cmd = con.CreateCommand()
                cmd.CommandText = "INSERT INTO table2(something)VALUES(@something)"
                cmd.Parameters.AddWithValue("@something", something)
                con.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Using 
    Catch ex As Exception
        msgbox(ex.tostring())
    End Try 
    
        2
  •  0
  •   Bozhidar Stoyneff    6 年前

    这是一个并发问题。因为代码的其他部分或MS Access本身会同时访问数据库。 事实上,在使用连接后,您不会关闭它。因此,第二次调用应该会失败,并出现该异常。相反,您应该将一次性用品(例如OleDbConnection、命令等)包装在using语句中。这样,即使发生异常,连接也将关闭:

        Using con As New OleDbConnection, cmd1 As OleDbCommand = con.CreateCommand, cmd2 As OleDbCommand = con.CreateCommand()
            cmd1.CommandText = "INSERT INTO table1(something)VALUES(something)"
            cmd1.ExecuteNonQuery()
    
            cmd2.CommandText = "INSERT INTO table2(something)VALUES(something)"
            cmd2.ExecuteNonQuery()
        End Using