Runtime error 3704 операция не допускается если объект закрыт
В моем vb6 я получаю ошибку 3704: операция не разрешена, когда объект закрыт.
У меня есть поисковый stackoverflow для аналогичной проблемы, но я думаю, что что-то упускаю. Мне нужно обновить каждую строку в vfp на основе набора записей rs1 Вот мой код:
задан 30 мая '11, 03:05
4 ответы
Запрос на обновление не возвращает набор записей, поэтому ваш rs2 не открывается.
ответ дан 30 мая '11, 07:05
Спасибо за ответ, Арво. Но когда я не помещаю код do while. Обновляется только одна запись. Мне нужно обновить каждую строку в rs2 из rs1. Вы можете посоветовать мне, пожалуйста, - Моншайн
Почему вы используете функцию открытия набора записей для обновлений? Почему вы зацикливаетесь на RS2? Сколько записей в rs1, какая из них вам интересна? Почему нельзя использовать для обновления операции на основе наборов? Думаю, у вашей программы логика тоже не очень ясна. - Арво
У VFP Provider есть несколько забавных ограничений. SELECT INTO и INSERT INTO, вероятно, не работают, даже если вы можете использовать связанную таблицу и т. Д. - Bob77
Вы выполняете свой цикл на неправильном записывающем наборе: я заменил некоторые из rs2 на rs1 в вашем коде.
ответ дан 30 мая '11, 14:05
Возможно, лучше избавиться от rs2 и использовать вместо него cn1.Execute, это не то, для чего предназначен Recordset. Избавьтесь от двойного отрицания «Do While Not EOF» и используйте вместо него «Do While Not EOF». Не проверяйте EOF второй раз внутри цикла, это бессмысленно. Вы уверены, что хотите здесь ОБНОВЛЕНИЕ, а не ВСТАВИТЬ? - Bob77
@Bob Riemersma Я согласен с вами, и в этом коде все еще есть сто ошибок, которые можно (или нужно) улучшить. Я стараюсь помочь пользователю, внося минимальные изменения в его код. Между тем, я настоятельно рекомендую вам написать собственный ответ. - ДавРоб60
Арво, @ Bob Riemersma. Большое спасибо за вашу помощь. Да, мне нужно обновить таблицу vfp. Я создал связанный сервер в sql, но я не мог его обновить. Поэтому я вызываю rs1 из sql, а затем обновляю vfp в vb6.Я буду признателен, если вы подскажете мне, какое решение лучше всего реализовать. Еще раз спасибо за ваше время. - Моншайн
Вам не нужно создавать набор записей для выполнения обновления, вставки или удаления в базе данных. Просто используйте оператор cn1.Execute YourSqlStatement, где YourSqlStatement - это строка, которую вы передаете инструкции rs2.Open. Метод Execute в соединении дополнительно принимает переменную byRef, в которой вы можете получить количество затронутых записей.
В этой статье представлена ошибка с номером Ошибка 3704, известная как Вы попытались открыть базу данных, которая уже открыта пользователем '| 2' на компьютере '| 1', описанная как Вы попытались открыть базу данных, которая уже открыта пользователем «| 2» на компьютере «| 1». Повторите попытку, когда база данных станет доступной.
Информация об ошибке
Имя ошибки: Вы попытались открыть базу данных, которая уже открыта пользователем '| 2' на компьютере '| 1'
Номер ошибки: Ошибка 3704
Описание: Вы попытались открыть базу данных, которая уже открыта пользователем «| 2» на компьютере «| 1». Повторите попытку, когда база данных станет доступной.
Программное обеспечение: Microsoft Access
Разработчик: Microsoft
Этот инструмент исправления может устранить такие распространенные компьютерные ошибки, как BSODs, зависание системы и сбои. Он может заменить отсутствующие файлы операционной системы и библиотеки DLL, удалить вредоносное ПО и устранить вызванные им повреждения, а также оптимизировать ваш компьютер для максимальной производительности.
О программе Runtime Ошибка 3704
Время выполнения Ошибка 3704 происходит, когда Microsoft Access дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.
Определения (Бета)
Здесь мы приводим некоторые определения слов, содержащихся в вашей ошибке, в попытке помочь вам понять вашу проблему. Эта работа продолжается, поэтому иногда мы можем неправильно определить слово, так что не стесняйтесь пропустить этот раздел!
- База данных . База данных - это организованный набор данных.
Симптомы Ошибка 3704 - Вы попытались открыть базу данных, которая уже открыта пользователем '| 2' на компьютере '| 1'
Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.
(Только для примера)
Причины Вы попытались открыть базу данных, которая уже открыта пользователем '| 2' на компьютере '| 1' - Ошибка 3704
При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.
Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.
Методы исправления
Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.
Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.
«Excel Error 3704» часто называется ошибкой во время выполнения (ошибка). Разработчики программного обеспечения, такие как Microsoft Corporation, обычно принимают Microsoft Excel через несколько уровней отладки, чтобы сорвать эти ошибки перед выпуском для общественности. К сожалению, инженеры являются людьми и часто могут делать ошибки во время тестирования, отсутствует ошибка 3704.
Источники проблем Excel Error 3704
Заражение вредоносными программами, недопустимые записи реестра Microsoft Excel или отсутствующие или поврежденные файлы Excel Error 3704 могут создать эти ошибки Excel Error 3704.
«You attempted to open a database that is already opened by user '|2' on machine '|1'» также считается ошибкой во время выполнения (ошибкой). Разработчики, такие как Microsoft Corporation, обычно проходят через несколько контрольных точек перед запуском программного обеспечения, такого как Microsoft Access. К сожалению, такие проблемы, как ошибка 3704, могут быть пропущены, и программное обеспечение будет содержать эти проблемы при выпуске.
Run-time error '3704' - Operation is not allowed when the object is closed
I got this error despite the fact i have used almost exactly the same code before and it worked perfectly well, no idea why i am getting this error saying "Operation is not allowed when the object is closed" and as you can see in the code below the object is not closed, any help please? there is no problem in the SQL code in the Setup page whatsoever.
Thanks guy for your help.
Member Join Date Feb 2016 Posts 39
Wall Poster Join Date Sep 2002 Location Columbus, Ohio Posts 3,647
Double check your SQL actually returns data. For example a stored procedure that brings back nothing can do that.
Member Join Date Feb 2016 Posts 39
Hi Tyson, there is no problem with the code and in SQL it returns 22 rows, i just don't know what the problem is as i've used very similar VBA code before !!
Wall Poster Join Date Sep 2002 Location Columbus, Ohio Posts 3,647
Just for grins right before the open add this:
strSql = "Select 'JUNK' as 'JUNK'"
That will guarantee something will come back.
I just want to be sure something comes back, not that I doubt you
PowerPoster Join Date Feb 2012 Location West Virginia Posts 14,057
Member Join Date Feb 2016 Posts 39
No chance guys, nothing worked so far and the code returns data in SQL but not through VBA, any more help please!! this error should be common but can't get my head around it !
PowerPoster Join Date Jun 2015 Posts 2,224
Wall Poster Join Date Sep 2002 Location Columbus, Ohio Posts 3,647
Originally Posted by DEXWERX
Wall Poster Join Date Sep 2002 Location Columbus, Ohio Posts 3,647
It seems easy but I don't do much with VBA. If it was me I would try this to prove the connections are all working. Similar to DEXWERX's suggestion about displaying the state.
Super Moderator Join Date Aug 2002 Location Idaho Posts 37,296
PowerPoster Join Date Dec 2004 Posts 25,572
the error is specific, rs.Open strSql, cn has to be failing to open a recordset, though i would have expected an error to occur
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
PowerPoster Join Date Feb 2012 Location West Virginia Posts 14,057
Originally Posted by SamVBA1
No chance guys, nothing worked so far and the code returns data in SQL but not through VBA, any more help please!! this error should be common but can't get my head around it !
Did you use debug.print to see the actual query you are building as it is when it is used to open the recordset.
From your code snippet we don't have a clue what that query might look like. You appear to be looping through some cells and taking what is there to build your query when the one cell = postings. It seems that your code is failing to open the RS and the most likely reason for that is failure of the query
Member Join Date Feb 2016 Posts 39
Westconn1, why would you expect an error to happen, i've used almost the same vba code before and didn't have any problem whatsoever.
Member Join Date Feb 2016 Posts 39
DataMiser, I am using the loop to read data in cells A from row 5 to row 25 (now i just changed it to row 17), i used this technique before and there should be no problem with the code at all, have a look at the SQL query , i am pretty sure it has no problem, why the recordset is closed i have no idea ..Thanks.
PowerPoster Join Date Dec 2004 Posts 25,572
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Member Join Date Feb 2016 Posts 39
PowerPoster Join Date Dec 2004 Posts 25,572
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Member Join Date Feb 2016 Posts 39
SQL server database, i tried very simple code and i had the same error, so nothing to do with the SQL query or SQL tables, it's just weird!
Wall Poster Join Date Sep 2002 Location Columbus, Ohio Posts 3,647
The error message is telling you exactly what is wrong. You keep saying there is nothing wrong with the SQL but there is. Please post it and also display the connection states as previously posted.
I've made this simple mistake more that once. I'll be looking at the wrong database when running the query in native SQL versus what the program is connected to. I'd verify that isn't happening also.
Member Join Date Feb 2016 Posts 39
PowerPoster Join Date Dec 2004 Posts 25,572
Describes for all applicable objects whether the state of the object is open or closed.
Describes for a Recordset object executing an asynchronous method, whether the current state of the object is connecting, executing, or fetching.
Returns a Long value that can be one of the following constants.
Constant Description
adStateClosed Default. Indicates that the object is closed.
adStateOpen Indicates that the object is open.
adStateConnecting Indicates that the Recordset object is connecting.
adStateExecuting Indicates that the Recordset object is executing a command.
adStateFetching Indicates that the rows of the Recordset object are being fetched.
You can use the State property to determine the current state of a given object at any time. This property is read-only.
The Recordset object’s State property can have a combination of values. For example, if a statement is executing, this property will have a combined value of adStateOpen and adStateExecuting.
if the sql query takes some time to execute, you may need to loop until open, a poor database with a complex query may take some considerable time to return the recordset
i have had queries took more than � hr to return on a basic join of 2 tables
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Wall Poster Join Date Sep 2002 Location Columbus, Ohio Posts 3,647
Originally Posted by SamVBA1
That looks like text in a spreadsheet to me.
I'm afraid I don't have much more to offer but please post the resolution when you find it.
Member Join Date Feb 2016 Posts 39
Originally Posted by westconn1
if the sql query takes some time to execute, you may need to loop until open, a poor database with a complex query may take some considerable time to return the recordset
i have had queries took more than � hr to return on a basic join of 2 tables
I've done what you suggested and wrote this:
at the second line i got message "1" meaning the connection is open, but at the last step "If rs.State = adStateClosed Then MsgBox "recordset failed to open" i got a message "recordset failed to open". so it was opened and it seems it closed again!! what happened exactly here between these two message lines! there is no problem with the code whatsoever! i hope the problem is clearer to you now.
Wall Poster Join Date Sep 2002 Location Columbus, Ohio Posts 3,647
Originally Posted by SamVBA1
I've done what you suggested and wrote this:
at the second line i got message "1" meaning the connection is open, but at the last step "If rs.State = adStateClosed Then MsgBox "recordset failed to open" i got a message "recordset failed to open". so it was opened and it seems it closed again!! what happened exactly here between these two message lines! there is no problem with the code whatsoever! i hope the problem is clearer to you now.
PowerPoster Join Date Oct 2008 Location Midwest Region, United States Posts 3,574
Member Join Date Feb 2016 Posts 39
Originally Posted by vbfbryce
Actually i didn't use both i only needed "rs.Open strSql, cn" but still tried all options but it didn't work mate
PowerPoster Join Date Dec 2004 Posts 25,572
NO, the first tells the connection is open, which we already believed, else you would have some other error, maybe object required, when trying to open the recordset
the second tells that the recordset is not open, which we also already knew as the error you are getting specifically tells the recordset is closed
i would believe, the only reason the recordset can fail to open is that your sql is not valid
if you sql was valid, but returned no records, rs.eof would be true, but no error
try simpler queries, then build up the sting till you find which part is causing the problem
test how long the queries take to execute
use debug.print strsql, to see how the sql looks in the immediate window, you could then paste it in this thread, someone (probably not me) may see some issue in it, or it may be better to post the sql query in the database forum, make sure to specify which database you are using
your problem is the sql query, no one can test it for you, as it is only relevant to your database
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Member Join Date Feb 2016 Posts 39
Originally Posted by westconn1
NO, the first tells the connection is open, which we already believed, else you would have some other error, maybe object required, when trying to open the recordset
the second tells that the recordset is not open, which we also already knew as the error you are getting specifically tells the recordset is closed
i would believe, the only reason the recordset can fail to open is that your sql is not valid
if you sql was valid, but returned no records, rs.eof would be true, but no error
try simpler queries, then build up the sting till you find which part is causing the problem
test how long the queries take to execute
use debug.print strsql, to see how the sql looks in the immediate window, you could then paste it in this thread, someone (probably not me) may see some issue in it, or it may be better to post the sql query in the database forum, make sure to specify which database you are using
your problem is the sql query, no one can test it for you, as it is only relevant to your database
Thanks mate, i promise i tried a very simple SQL query that definitely return data and i got the same error, can you tell me where to insert the "debug.print strSql exactly? Thanks
Источники проблем You attempted to open a database that is already opened by user '|2' on machine '|1'
Большинство проблем You attempted to open a database that is already opened by user '|2' on machine '|1' связаны с отсутствующим или поврежденным You attempted to open a database that is already opened by user '|2' on machine '|1', вирусной инфекцией или недействительными записями реестра Windows, связанными с Microsoft Access.
Точнее, ошибки You attempted to open a database that is already opened by user '|2' on machine '|1', созданные из:
Member Join Date Feb 2016 Posts 39
Что вызывает ошибку 3704 во время выполнения?
Сбой во время запуска Microsoft Excel или во время выполнения, как правило, когда вы столкнетесь с «Excel Error 3704». Вот три наиболее распространенные причины, по которым происходят ошибки во время выполнения ошибки 3704:
Ошибка 3704 Crash - ошибка 3704 блокирует любой вход, и это может привести к сбою машины. Это возникает, когда Microsoft Excel не реагирует на ввод должным образом или не знает, какой вывод требуется взамен.
Утечка памяти «Excel Error 3704» - ошибка 3704 утечка памяти приводит к увеличению размера Microsoft Excel и используемой мощности, что приводит к низкой эффективности систем. Возможные искры включают сбой освобождения, который произошел в программе, отличной от C ++, когда поврежденный код сборки неправильно выполняет бесконечный цикл.
Ошибка 3704 Logic Error - «логическая ошибка», как говорят, генерируется, когда программное обеспечение получает правильный ввод, но генерирует неверный вывод. Это видно, когда исходный код Microsoft Corporation включает дефект в анализе входных данных.
Почему и когда срабатывает ошибка времени выполнения 3704?
Сбой во время выполнения Microsoft Access, как правило, когда вы столкнетесь с «You attempted to open a database that is already opened by user '|2' on machine '|1'» в качестве ошибки во время выполнения. Это три основных триггера для ошибок во время выполнения, таких как ошибка 3704:
Ошибка 3704 Crash - Ошибка 3704 остановит компьютер от выполнения обычной программной операции. Если данный ввод недействителен или не соответствует ожидаемому формату, Microsoft Access (или OS) завершается неудачей.
Утечка памяти «You attempted to open a database that is already opened by user '|2' on machine '|1'» - последствия утечки памяти Microsoft Access связаны с неисправной операционной системой. Возможные причины из-за отказа Microsoft Corporation девыделения памяти в программе или когда плохой код выполняет «бесконечный цикл».
Ошибка 3704 Logic Error - Логические ошибки проявляются, когда пользователь вводит правильные данные, но устройство дает неверный результат. Это происходит, когда исходный код Microsoft Corporation вызывает уязвимость при обработке информации.
Такие проблемы You attempted to open a database that is already opened by user '|2' on machine '|1' обычно вызваны повреждением файла, связанного с Microsoft Access, или, в некоторых случаях, его случайным или намеренным удалением. Как правило, решить проблему позволяет получение новой копии файла Microsoft Corporation, которая не содержит вирусов. Кроме того, регулярная очистка и оптимизация реестра Windows предотвратит создание неправильных ссылок на пути к файлам Microsoft Corporation, поэтому мы настоятельно рекомендуем регулярно выполнять сканирование реестра.
Ошибки You attempted to open a database that is already opened by user '|2' on machine '|1'
Эти проблемы Microsoft Access, связанные с You attempted to open a database that is already opened by user '|2' on machine '|1', включают в себя:
- «Ошибка в приложении: You attempted to open a database that is already opened by user '|2' on machine '|1'»
- "You attempted to open a database that is already opened by user '|2' on machine '|1' не является приложением Win32."
- «Извините, You attempted to open a database that is already opened by user '|2' on machine '|1' столкнулся с проблемой. «
- «You attempted to open a database that is already opened by user '|2' on machine '|1' не может быть найден. «
- «You attempted to open a database that is already opened by user '|2' on machine '|1' не может быть найден. «
- "Ошибка запуска программы: You attempted to open a database that is already opened by user '|2' on machine '|1'."
- «Не удается запустить You attempted to open a database that is already opened by user '|2' on machine '|1'. «
- «You attempted to open a database that is already opened by user '|2' on machine '|1' выйти. «
- «Ошибка пути программного обеспечения: You attempted to open a database that is already opened by user '|2' on machine '|1'. «
Классические проблемы Excel Error 3704
Наиболее распространенные ошибки Excel Error 3704, которые могут возникнуть на компьютере под управлением Windows, перечислены ниже:
- «Ошибка Excel Error 3704. «
- «Ошибка программного обеспечения Win32: Excel Error 3704»
- «Извините, Excel Error 3704 столкнулся с проблемой. «
- "Файл Excel Error 3704 не найден."
- "Отсутствует файл Excel Error 3704."
- "Ошибка запуска программы: Excel Error 3704."
- "Файл Excel Error 3704 не запущен."
- «Excel Error 3704 выйти. «
- «Excel Error 3704: путь приложения является ошибкой. «
Читайте также: