我想在2个不同的table of ms-access
中插入2个不同的数据。
它显示了这个错误。
我有这样的代码:
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.)
所以,我该怎么办?
感谢任何帮助。谢谢
答案 0 :(得分:2)
我认为关闭连接可以解决问题,最好使用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
答案 1 :(得分:0)
这是一个并发问题。因为代码的某些其他部分或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