Runtime error 3146 odbc ошибка вызова

My client is using Access as a front end to a SQL Server database. They recently started getting ODBC — 3146 errors from time to time when running some reports. From what I can tell, this is just a generic ODBC call failed error.

I’ve tried sticking some error handling in the VB script that is launching the reports, but I am not having any luck getting extra error information.

Code looks a bit like this.

Public Function RunReports()
  On Error GoTo MyErrorTrap

  DoCmd.OpenReport "blah", acViewPreview
  DoCmd.Close

  DoCmd.OpenReport "foo", acViewPreview
  DoCmd.Close

Exit_function:
  Exit Function

MyErrorTrap:
  Dim errX As DAO.Error
  Dim MyError As Error
  If Errors.Count > 1   'This always seems to be 0, so no help
    For Each errX In DAO.Errors  'These are empty even if dont check for Errors.Count
      Debug.Print "ODBC Error"
      Debug.Print errX.Number
      Debug.Print errX.Description
    Next errX
  Else
    Debug.Print "VBA Error"
    Debug.Print Err.Number
    Debug.Print Err.Description
  End If

  'Also have tried checking DBEngine.Errors, but this is empty too

End Function

I’ve also enabled tracing on the ODBC side, but that has bogged things down way too much, and I am so far unable to recreate the ODBC error.

I am completely open for suggestions on how to diagnose this.

В этой статье представлена ошибка с номером Ошибка 3146, известная как Ошибка Microsoft Access 3146, описанная как ODBC — вызов не удался.

О программе Runtime Ошибка 3146

Время выполнения Ошибка 3146 происходит, когда Microsoft Access дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.

Определения (Бета)

Здесь мы приводим некоторые определения слов, содержащихся в вашей ошибке, в попытке помочь вам понять вашу проблему. Эта работа продолжается, поэтому иногда мы можем неправильно определить слово, так что не стесняйтесь пропустить этот раздел!

  • Доступ — НЕ ИСПОЛЬЗУЙТЕ этот тег для Microsoft Access, используйте вместо него [ms-access]
  • Вызов — Вызов действие по вызову подпрограммы кода, внешней программы или сценария в среде программирования.
  • Odbc — Open Database Connectivity ODBC предоставляет стандартный программный интерфейс для доступа к СУБД систем управления базами данных .
  • Access — Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft, которая обычно сочетает в себе реляционную СУБД Microsoft JetACE с графическим пользовательским интерфейсом и программным обеспечением. -инструменты разработки.
  • Доступ к Microsoft — Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft, которая обычно объединяет реляционное ядро ​​СУБД Microsoft JetACE с графическим пользователем. интерфейс и средства разработки программного обеспечения
Симптомы Ошибка 3146 — Ошибка Microsoft Access 3146

Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.

Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.

Fix Ошибка Microsoft Access 3146 (Error Ошибка 3146)
(Только для примера)

Причины Ошибка Microsoft Access 3146 — Ошибка 3146

При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.

Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.

Методы исправления

Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.

Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.

Обратите внимание: ни ErrorVault.com, ни его авторы не несут ответственности за результаты действий, предпринятых при использовании любого из методов ремонта, перечисленных на этой странице — вы выполняете эти шаги на свой страх и риск.

Метод 1 — Закройте конфликтующие программы

Когда вы получаете ошибку во время выполнения, имейте в виду, что это происходит из-за программ, которые конфликтуют друг с другом. Первое, что вы можете сделать, чтобы решить проблему, — это остановить эти конфликтующие программы.

  • Откройте диспетчер задач, одновременно нажав Ctrl-Alt-Del. Это позволит вам увидеть список запущенных в данный момент программ.
  • Перейдите на вкладку «Процессы» и остановите программы одну за другой, выделив каждую программу и нажав кнопку «Завершить процесс».
  • Вам нужно будет следить за тем, будет ли сообщение об ошибке появляться каждый раз при остановке процесса.
  • Как только вы определите, какая программа вызывает ошибку, вы можете перейти к следующему этапу устранения неполадок, переустановив приложение.

Метод 2 — Обновите / переустановите конфликтующие программы

Использование панели управления

  • В Windows 7 нажмите кнопку «Пуск», затем нажмите «Панель управления», затем «Удалить программу».
  • В Windows 8 нажмите кнопку «Пуск», затем прокрутите вниз и нажмите «Дополнительные настройки», затем нажмите «Панель управления»> «Удалить программу».
  • Для Windows 10 просто введите «Панель управления» в поле поиска и щелкните результат, затем нажмите «Удалить программу».
  • В разделе «Программы и компоненты» щелкните проблемную программу и нажмите «Обновить» или «Удалить».
  • Если вы выбрали обновление, вам просто нужно будет следовать подсказке, чтобы завершить процесс, однако, если вы выбрали «Удалить», вы будете следовать подсказке, чтобы удалить, а затем повторно загрузить или использовать установочный диск приложения для переустановки. программа.

Использование других методов

  • В Windows 7 список всех установленных программ можно найти, нажав кнопку «Пуск» и наведя указатель мыши на список, отображаемый на вкладке. Вы можете увидеть в этом списке утилиту для удаления программы. Вы можете продолжить и удалить с помощью утилит, доступных на этой вкладке.
  • В Windows 10 вы можете нажать «Пуск», затем «Настройка», а затем — «Приложения».
  • Прокрутите вниз, чтобы увидеть список приложений и функций, установленных на вашем компьютере.
  • Щелкните программу, которая вызывает ошибку времени выполнения, затем вы можете удалить ее или щелкнуть Дополнительные параметры, чтобы сбросить приложение.

Метод 3 — Обновите программу защиты от вирусов или загрузите и установите последнюю версию Центра обновления Windows.

Заражение вирусом, вызывающее ошибку выполнения на вашем компьютере, необходимо немедленно предотвратить, поместить в карантин или удалить. Убедитесь, что вы обновили свою антивирусную программу и выполнили тщательное сканирование компьютера или запустите Центр обновления Windows, чтобы получить последние определения вирусов и исправить их.

Метод 4 — Переустановите библиотеки времени выполнения

Вы можете получить сообщение об ошибке из-за обновления, такого как пакет MS Visual C ++, который может быть установлен неправильно или полностью. Что вы можете сделать, так это удалить текущий пакет и установить новую копию.

  • Удалите пакет, выбрав «Программы и компоненты», найдите и выделите распространяемый пакет Microsoft Visual C ++.
  • Нажмите «Удалить» в верхней части списка и, когда это будет сделано, перезагрузите компьютер.
  • Загрузите последний распространяемый пакет от Microsoft и установите его.

Метод 5 — Запустить очистку диска

Вы также можете столкнуться с ошибкой выполнения из-за очень нехватки свободного места на вашем компьютере.

  • Вам следует подумать о резервном копировании файлов и освобождении места на жестком диске.
  • Вы также можете очистить кеш и перезагрузить компьютер.
  • Вы также можете запустить очистку диска, открыть окно проводника и щелкнуть правой кнопкой мыши по основному каталогу (обычно это C :)
  • Щелкните «Свойства», а затем — «Очистка диска».

Метод 6 — Переустановите графический драйвер

Если ошибка связана с плохим графическим драйвером, вы можете сделать следующее:

  • Откройте диспетчер устройств и найдите драйвер видеокарты.
  • Щелкните правой кнопкой мыши драйвер видеокарты, затем нажмите «Удалить», затем перезагрузите компьютер.

Метод 7 — Ошибка выполнения, связанная с IE

Если полученная ошибка связана с Internet Explorer, вы можете сделать следующее:

  1. Сбросьте настройки браузера.
    • В Windows 7 вы можете нажать «Пуск», перейти в «Панель управления» и нажать «Свойства обозревателя» слева. Затем вы можете перейти на вкладку «Дополнительно» и нажать кнопку «Сброс».
    • Для Windows 8 и 10 вы можете нажать «Поиск» и ввести «Свойства обозревателя», затем перейти на вкладку «Дополнительно» и нажать «Сброс».
  2. Отключить отладку скриптов и уведомления об ошибках.
    • В том же окне «Свойства обозревателя» можно перейти на вкладку «Дополнительно» и найти пункт «Отключить отладку сценария».
    • Установите флажок в переключателе.
    • Одновременно снимите флажок «Отображать уведомление о каждой ошибке сценария», затем нажмите «Применить» и «ОК», затем перезагрузите компьютер.

Если эти быстрые исправления не работают, вы всегда можете сделать резервную копию файлов и запустить восстановление на вашем компьютере. Однако вы можете сделать это позже, когда перечисленные здесь решения не сработают.

Другие языки:

How to fix Error 3146 (Microsoft Access Error 3146) — ODBC—call failed.
Wie beheben Fehler 3146 (Microsoft Access-Fehler 3146) — ODBC—Aufruf fehlgeschlagen.
Come fissare Errore 3146 (Errore di Microsoft Access 3146) — ODBC: chiamata non riuscita.
Hoe maak je Fout 3146 (Microsoft Access-fout 3146) — ODBC—aanroep mislukt.
Comment réparer Erreur 3146 (Erreur Microsoft Access 3146) — ODBC—l’appel a échoué.
어떻게 고치는 지 오류 3146 (마이크로소프트 액세스 오류 3146) — ODBC—호출에 실패했습니다.
Como corrigir o Erro 3146 (Erro 3146 do Microsoft Access) — ODBC — falha na chamada.
Hur man åtgärdar Fel 3146 (Microsoft Access-fel 3146) — ODBC-samtal misslyckades.
Jak naprawić Błąd 3146 (Błąd Microsoft Access 3146) — ODBC — wywołanie nie powiodło się.
Cómo arreglar Error 3146 (Error 3146 de Microsoft Access) — ODBC: la llamada falló.

The Author Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.

Следуйте за нами: Facebook Youtube Twitter

Последнее обновление:

24/05/22 01:21 : Пользователь Android проголосовал за то, что метод восстановления 1 работает для него.

Рекомендуемый инструмент для ремонта:

Этот инструмент восстановления может устранить такие распространенные проблемы компьютера, как синие экраны, сбои и замораживание, отсутствующие DLL-файлы, а также устранить повреждения от вредоносных программ/вирусов и многое другое путем замены поврежденных и отсутствующих системных файлов.

ШАГ 1:

Нажмите здесь, чтобы скачать и установите средство восстановления Windows.

ШАГ 2:

Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.

ШАГ 3:

Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.

СКАЧАТЬ СЕЙЧАС

Совместимость

Требования

1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.

ID статьи: ACX06523RU

Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000

Icon Ex Номер ошибки: Ошибка 3146
Название ошибки: Microsoft Access Error 3146
Описание ошибки: ODBC—call failed.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Access
Относится к: Windows XP, Vista, 7, 8, 10, 11

Обзор «Microsoft Access Error 3146»

Как правило, практикующие ПК и сотрудники службы поддержки знают «Microsoft Access Error 3146» как форму «ошибки во время выполнения». Когда дело доходит до Microsoft Access, инженеры программного обеспечения используют арсенал инструментов, чтобы попытаться сорвать эти ошибки как можно лучше. К сожалению, многие ошибки могут быть пропущены, что приводит к проблемам, таким как те, с ошибкой 3146.

Некоторые люди могут столкнуться с сообщением «ODBC—call failed.» во время работы программного обеспечения. Сообщение об этой ошибке 3146 позволит разработчикам обновить свое приложение и исправить любые ошибки, которые могут вызвать его. Затем Microsoft Corporation исправит ошибки и подготовит файл обновления для загрузки. Эта ситуация происходит из-за обновления программного обеспечения Microsoft Access является одним из решений ошибок 3146 ошибок и других проблем.

«Microsoft Access Error 3146» чаще всего может возникать при загрузке Microsoft Access. Рассмотрим распространенные причины ошибок ошибки 3146 во время выполнения:

Ошибка 3146 Crash — Ошибка 3146 является хорошо известной, которая происходит, когда неправильная строка кода компилируется в исходный код программы. Это возникает, когда Microsoft Access не реагирует на ввод должным образом или не знает, какой вывод требуется взамен.

Утечка памяти «Microsoft Access Error 3146» — если есть утечка памяти в Microsoft Access, это может привести к тому, что ОС будет выглядеть вялой. Возможные искры включают сбой освобождения, который произошел в программе, отличной от C ++, когда поврежденный код сборки неправильно выполняет бесконечный цикл.

Ошибка 3146 Logic Error — логическая ошибка возникает, когда Microsoft Access производит неправильный вывод из правильного ввода. Когда точность исходного кода Microsoft Corporation низкая, он обычно становится источником ошибок.

Как правило, такие Microsoft Corporation ошибки возникают из-за повреждённых или отсутствующих файлов Microsoft Access Error 3146, а иногда — в результате заражения вредоносным ПО в настоящем или прошлом, что оказало влияние на Microsoft Access. Как правило, решить проблему можно заменой файла Microsoft Corporation. Помимо прочего, в качестве общей меры по профилактике и очистке мы рекомендуем использовать очиститель реестра для очистки любых недопустимых записей файлов, расширений файлов Microsoft Corporation или разделов реестра, что позволит предотвратить появление связанных с ними сообщений об ошибках.

Ошибки Microsoft Access Error 3146

Эти проблемы Microsoft Access, связанные с Microsoft Access Error 3146, включают в себя:

  • «Ошибка программы Microsoft Access Error 3146. «
  • «Недопустимая программа Win32: Microsoft Access Error 3146»
  • «Извините, Microsoft Access Error 3146 столкнулся с проблемой. «
  • «Microsoft Access Error 3146 не может быть найден. «
  • «Microsoft Access Error 3146 не найден.»
  • «Ошибка запуска программы: Microsoft Access Error 3146.»
  • «Microsoft Access Error 3146 не работает. «
  • «Ошибка Microsoft Access Error 3146. «
  • «Неверный путь к программе: Microsoft Access Error 3146. «

Обычно ошибки Microsoft Access Error 3146 с Microsoft Access возникают во время запуска или завершения работы, в то время как программы, связанные с Microsoft Access Error 3146, выполняются, или редко во время последовательности обновления ОС. Важно отметить, когда возникают проблемы Microsoft Access Error 3146, так как это помогает устранять проблемы Microsoft Access (и сообщать в Microsoft Corporation).

Создатели Microsoft Access Error 3146 Трудности

Заражение вредоносными программами, недопустимые записи реестра Microsoft Access или отсутствующие или поврежденные файлы Microsoft Access Error 3146 могут создать эти ошибки Microsoft Access Error 3146.

В частности, проблемы Microsoft Access Error 3146 возникают через:

  • Недопустимая или поврежденная запись Microsoft Access Error 3146.
  • Вредоносные программы заразили Microsoft Access Error 3146, создавая повреждение.
  • Другая программа (не связанная с Microsoft Access) удалила Microsoft Access Error 3146 злонамеренно или по ошибке.
  • Другая программа, конфликтующая с Microsoft Access Error 3146 или другой общей ссылкой Microsoft Access.
  • Microsoft Access (Microsoft Access Error 3146) поврежден во время загрузки или установки.

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

  • Remove From My Forums
  • Вопрос

  • Hi all,

    I have  a MSaccess front end and SQL server 2005 back end. The functionality is that in the front-end VBA code the application compares the data in the text files which are linked to the application with the data in the tables in SQL server and updates
    the SQL server tables.

    My problem is that whenever there is a key constraint violated or we try to insert duplicates into the primary key or any other error …. The message box shows only :

    error 3146: ODBC link Failed.

     There is no detailed descrition like the one we get in SQL server where the error and the cause both are shown. Is there a way to retreive the entire error???

    Note: This question has not been answered in any previous post. kindly do not think otherwise.

    Thanks in advance.

Ответы

  • I assume that you are using the ODBC DSN for communicating with the backend SQL Server 2005 DB from your front end Access Application. Can you enable ODBC logging following the instructions in :
    http://support.microsoft.com/kb/274551 [How To Generate an ODBC Trace with ODBC Data Source Administrator]

    This ODBC trace can give you more details about the exceptions you see on the application..

    Note: Do not forget to turn tracing off when you are done with the troubleshooting. If you keep tracing set to on, it degrades your application performance.

    Hope this helps..


    Chaitanya( Twitter |
    Blogs )

    Any documentation bug? Tell us about it at
    Connect. Please feel free to add any community comments in any of the MSDN/technet articles.
    This posting is provided «AS IS» with no warranties, and confers no rights.

    The next CTP for SQL Server Code Name «Denali» is coming soon.
    Sign up now to be notified of the next CTP release.

    • Помечено в качестве ответа

      13 июля 2011 г. 7:41

  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • RUNTIME ERROR ‘3146’..ODBC-Call Failed

  1. May 9th, 2005, 11:41 PM

    #1

    nagasrikanth is offline

    Thread Starter


    Hyperactive Member

    nagasrikanth's Avatar


    Lightbulb RUNTIME ERROR ‘3146’..ODBC-Call Failed

    Hi..

    Im using SQL server as my backend and MS Access as F.E..

    Im using to update around 10 to 20 records one by one by upto 2 to 3 records it was updating, later for 4th record it was saying «RUNTIME ERROR ‘3146’..ODBC-Call Failed»(at «rst.update» it was showing)
    ..at that time if i start agian from «rst.addnew» then for upto 3 to 4 it was okay..Is there any limitation in adding records.???
    FYI: Im not getting if i update 1 or 2 records..and
    one more thing that i came to know was ,If the table was a ordinary Access Table..Im not getting any error..
    One more thing was If i place some time delay using msgbox (like msgbox «Updated…» for example)that means for each record I placed a message updated..then it was working perfectly on to my surprise..

    Please help me in this regard..Please..

    Thanks & regards
    Anu…


  2. May 9th, 2005, 11:46 PM

    #2

    Re: RUNTIME ERROR ‘3146’..ODBC-Call Failed

    Sounds like your updating/adding records through Access tables/queries and not directly to the SQL tables? Alos, probably
    using a recordset to add/update when you could execute a sql INSERT statement or an sql UPDATE statement.

    Recordsets are slow. You can create a connection to SQL using ADO, DAO, ODBC to perform your actions.

    VB/Office Guru� (AKA: Gangsta Yoda)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum. Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru� Word SpellChecker�.NETVB/Office Guru� Word SpellChecker� VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24″ LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6


  3. May 9th, 2005, 11:59 PM

    #3

    nagasrikanth is offline

    Thread Starter


    Hyperactive Member

    nagasrikanth's Avatar


    Lightbulb Re: RUNTIME ERROR ‘3146’..ODBC-Call Failed

    Hi Rob,
    Thanx for u r quick reply..
    But Im using SQL tables it self,(Sql tables are linked in my database..)
    and whenever i want to insert new records im opening a connection using
    set rst=currentdb.openrecordset(sql string…….)
    and im inserting a new row by using AddNew and Update methods (not by using sql Queries)

    What i have to do speed up my recordset..Please help..

    Thanx & Regards
    Srikanth


  4. May 10th, 2005, 12:09 AM

    #4

    Re: RUNTIME ERROR ‘3146’..ODBC-Call Failed

    The slowness is from Access having to connect its linked ODBC connection to your SQL db/table via a rs. You could
    execute a statement like so.

    VB Code:

    1. Dim lRecs As Long

    2.     Access.CurrentDb.Connection.Execute "INSERT INTO Table1 VALUES('Testing')", lRecs

    3.     MsgBox lRecs & " records added", vbOKOnly + vbInformation

    VB/Office Guru� (AKA: Gangsta Yoda)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum. Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru� Word SpellChecker�.NETVB/Office Guru� Word SpellChecker� VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24″ LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6


  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • RUNTIME ERROR ‘3146’..ODBC-Call Failed


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Question & Answer

Question

Using Microsoft® Access 97 and getting «ODBC—call failed (error 3146)» error message. However, in a DB2® CLI trace, you see the error to be «[IBM][CLI Driver][DB2] SQL0180N The syntax of the string representation of a datetime value is incorrect. SQLSTATE=22007».

Cause

The problem is that Microsoft Access is using SQL_C_DEFAULT instead of providing an actual data type during the SQLBindParameter() call. The SQL_C_DEFAULT data format for SQL_TYPE_TIME is a SQL_C_TYPE_TIME data structure. The SQL_C_DEFAULT data format for SQL_TYPE_TIMESTAMP is a SQL_C_TYPE_TIMESTAMP data structure. The SQL_C_DEFAULT data format for SQL_TYPE_DATE is a SQL_C_TYPE_DATE data structure

However, the buffers Microsoft Access gives DB2 contain SQL_C_CHAR data, i.e. ASCII data.

If you refer to ODBC Specification:

http://msdn2.microsoft.com/en-us/library/ms131462(SQL.100).aspx

you can see that the table clearly shows that when SQL_C_DEFAULT is provided for a
SQL_TYPE_TIME column, a SQL_C_TYPE_TIME structure is assumed; that when SQL_C_DEFAULT is provided for a SQL_TYPE_TIMESTAMP column, a SQL_C_TYPE_TIMESTAMP structure is assumed; and that when SQL_C_DEFAULT is provided for a SQL_TYPE_DATE column, a SQL_C_TYPE_DATE structure is assumed. These structures have the following definitions:

http://msdn2.microsoft.com/en-us/library/ms714556.aspx

e.g. struct tagTIME_STRUCT {
SQLUSMALLINT hour;
SQLUSMALLINT minute;
SQLUSMALLINT second;
} TIME_STRUCT;[a]

This is not a DB2 issue, but may be a Microsoft Access issue since these structures do not contain ASCII character data. However, DB2 has a workaround to satisfy IBM DB2 customers.

Answer

The following CLI Configuration Keywords were added to DB2 v8.1 fixpack 4 as a workaround (depending on the data type of concern):

MapTimeDescribe=1
MapTimeStampDescribe=1
MapDateDescribe=1

=============================================================================

For DB2 v7.2 customers:

This works in DB2 v7.2 because Microsoft Access gives DB2 a SQLType of SQL_CHAR during the SQLBindParameter() call. As such, DB2 will read SQL_C_CHAR data from the application specified buffer.

[{«Product»:{«code»:»SSEPGG»,»label»:»Db2 for Linux, UNIX and Windows»},»Business Unit»:{«code»:»BU058″,»label»:»IBM Infrastructure w/TPS»},»Component»:»Programming Interface — CLI»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»9.5;9.1;8″,»Edition»:»All Editions»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

  • Remove From My Forums
  • Question

  • All

    We have a Pervasive SQL server on which I try to make an ODBC-connection.  I have code below.  It fails on the last line with message runtime error 3146: ODBC-call failed.  The Pervasive ODBC Client is installed and the name of server and
    database is correct.  If I use the import ODBC-function in Access, it works as expected but I must link it by using VBA.

     Set db = CurrentDb
        Set td = db.TableDefs(strTable)
        If Err.Number <> 0 Then
            Set td = db.CreateTableDef(strTable)
            td.Connect = «ODBC;Driver={Pervasive ODBC Client Interface};ServerName=svPSQL;dbq=@Purch»
            td.SourceTableName = strTable
            db.TableDefs.Append td

    End If

Answers

  • I found the issue, the connection string has to be:

    td.Connect = «ODBC;Driver={Pervasive ODBC Interface};ServerName=svPSQL;dbq=@Purch»

    • Marked as answer by

      Tuesday, June 23, 2020 9:20 AM

  • Remove From My Forums
  • Question

  • Hi all,

    I have  a MSaccess front end and SQL server 2005 back end. The functionality is that in the front-end VBA code the application compares the data in the text files which are linked to the application with the data in the tables in SQL server and updates
    the SQL server tables.

    My problem is that whenever there is a key constraint violated or we try to insert duplicates into the primary key or any other error …. The message box shows only :

    error 3146: ODBC link Failed.

     There is no detailed descrition like the one we get in SQL server where the error and the cause both are shown. Is there a way to retreive the entire error???

    Note: This question has not been answered in any previous post. kindly do not think otherwise.

    Thanks in advance.

Answers

  • I assume that you are using the ODBC DSN for communicating with the backend SQL Server 2005 DB from your front end Access Application. Can you enable ODBC logging following the instructions in :
    http://support.microsoft.com/kb/274551 [How To Generate an ODBC Trace with ODBC Data Source Administrator]

    This ODBC trace can give you more details about the exceptions you see on the application..

    Note: Do not forget to turn tracing off when you are done with the troubleshooting. If you keep tracing set to on, it degrades your application performance.

    Hope this helps..


    Chaitanya( Twitter |
    Blogs )

    Any documentation bug? Tell us about it at
    Connect. Please feel free to add any community comments in any of the MSDN/technet articles.
    This posting is provided «AS IS» with no warranties, and confers no rights.

    The next CTP for SQL Server Code Name «Denali» is coming soon.
    Sign up now to be notified of the next CTP release.

    • Marked as answer by

      Wednesday, July 13, 2011 7:41 AM

The MS Access ODBC call failed 3146 error displays as a result of a faulty network connection. It occurs within the Access database when setting up the associated database on an additional PC. This runtime error 3146 typically stipulates that there was a problem with an ODBC connection or an SQL query being performed. However, the most important thing is how to fix it. (Below you can see the complete error message).

Access ODBC Call Failed 3146 Error

Well, if you are getting this error, don’t fret. In this guide, I have described the possible causes and a few workarounds to deal with ODBC – call failed. (Error 3146). Also, I have mentioned the best Access Repair Tool to fix this error by repairing the database corruption.

Rated Excellent on Trustpilot
Free MS Access Database Repair Tool
Repair corrupt MDB and ACCDB database files and recover deleted database tables, queries, indexes and records easily. Try Now!

Download
By clicking the button above and installing Stellar Repair for Access (14.8 MB), I acknowledge that I have read and agree to the End User License Agreement and Privacy Policy of this site.

Quick Fixes:

  • Check ODBC DSN Configuration
  • Remove ODBC 1.x Driver Manager
  • Verify the Database Connection
  • Check Permissions
  • Ensure to Update the MS Access
  • Repairing the Corrupt Database Using Compact & Repair
  • Automated Solution: Fix Access Database Corruption

What is Error 3146 On ODBC Call Failed Run Time Access?

When Microsoft Access tries to enter the SQL Server 2000 database with the help of the ODBC connection, it displays an Error 3146- ODBC Call Failed. The database has been set as a source of data for the system with the driver of SQL Server. Hence, on launching the .mdb application database could be attached and results are fetched. But while populating data on the combo box, it shows this error.

On the other hand, we can say, that the SQL server cannot return any number for a statement due to performing a wrong query, it can display this error. However, this error message triggers due to various reasons, such as:

  • Invalid Data Source Name (DSN
  • Due to Incorrect Connection String or Network Issues
  • Database Server Downtime
  • Permission Issues
  • Issues with SQL Syntax
  • ODBC Driver Issues
  • Server Configuration.

Follow the below step-wise methods carefully to troubleshoot error 3146 ODBC call failed.

Method 1- Check ODBC DSN Configuration

The very first solution that you have to try to tackle the situation is to check if ODBC Data Source Name (DSN) is properly configured. To verify this, you have to:

  • Type Control Panel in the search box & open the first result.
  • Then, go to “Windows Tools” >> “ODBC Data Sources“.

MS Access ODBC Call Failed 3146 Error

  • Now, you will see the DNS list >> click on DSN that you need to test.
  • Next, click on “Configure” option to view the configurations for the DSN.

MS Access ODBC Call Failed 3146 Error

  • After that, click on “Test Connection” button to complete the process.

Also Read: [ODBC Microsoft Access Driver] Cannot Update. Database Or Object Is Read-Only Error

Method 2- Remove ODBC 1.x Driver Manager

Another way to fix this issue it is advised to remove the ODBC 1.x Driver Manager (Odbc.dll) and replace it with ODBC 2.x Driver Manager (Odbc.dll) in the primary path.

Method 3- Verify the Database Connection

Whenever the running database server faces downtime, you’ll encounter various issues, including the ODBC call failed 3146 error. In such a situation, you will have to ensure that the target SQL server is running & accessible from a device where Microsoft Access is installed.

Method 4- Check Permissions

Sometimes, it happens that the lack of necessary permissions to access the external database can lead to runtime error 3146. In that case, you have to ensure that the user account that is used by Microsoft Access has the required permissions to access the database, this includes both read & write permissions.

Method 5- Ensure to Update the MS Access

Many users have reported that they have received ODBC -call failed error in Access due to running an outdated version of Access application. Therefore, ensure that your Microsoft Access is up to date. Microsoft occasionally releases updates that might include bug fixes & improvements.

Also Read: Access Run Time Error 3151 ODBC Connection Failed

Method 6- Fix MS Access ODBC Call Failed 3146 Error by Repairing the Corrupt Database

Sometimes, the ODBC call failed 3146 error in Microsoft Access occurs due to database corruption. In such a case, you can use Access’s Compact & Repair tool to repair it.

Here are the complete steps:

  1. Open the Access application.
  2. Go to the File >> Info.
  3. Find & click on the Compact & Repair Database option.

Fix MS Access ODBC Call Failed 3146 Error

Automated Solution: Fix Access Database Corruption

If all the above-mentioned solutions do not help to fix run time error 3146 ODBC call failed timeout expired error, I would suggest opting for a third-party tool that solves any sort of MS Access-related error that has occurred due to database corruption. The best available tool for this purpose is MS Access Repair and Recovery Tool.

This software not only fixes errors but also fixes the .mdb files or .acccdb files and recovers the data from your corrupted MS Access database.  You can also restore the indexes, tables, queries, and relations very easily by using this tool.

* By clicking the Download button above and installing Stellar Repair for Access (14.8 MB), I acknowledge that I have read and agree to the End User License Agreement and Privacy Policy of this site.

Steps To Fix MS Access Error 3146

access-repair-main-screen

access-repairing-completed

previous arrow

next arrow

Also Read: Resolve Access 1919 – Configuring ODBC Data Source Error

Wrap Up

By following the fixes listed above, you can surely resolve MS Access error 3146: Run-time 3146 ODBC Call Failed. Do try all the solutions and let us know whether those solutions worked for you or not.

Besides, if you are facing any other issue in your access database, feel free to ask your queries on our social accounts like Twitter.

tip Still having issues? Fix them with this Access repair tool:

This software repairs & restores all ACCDB/MDB objects including tables, reports, queries, records, forms, and indexes along with modules, macros, and other stuffs effectively.

  1. Download Stellar Repair for Access rated Great on Cnet (download starts on this page).
  2. Click Browse and Search option to locate corrupt Access database.
  3. Click Repair button to repair & preview the database objects.

Pearson Willey is a website content writer and long-form content planner. Besides this, he is also an avid reader. Thus he knows very well how to write an engaging content for readers. Writing is like a growing edge for him. He loves exploring his knowledge on MS Access & sharing tech blogs.

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Summary: The Access runtime error 3146 — ODBC call failed occurs when using VBA code to access the external database in Microsoft Access. It usually happens when the ODBC connection fails due to incorrect queries, corruption in database file, or any other reason. This blog will cover the possible causes of the runtime error 3146 in Access and the troubleshooting methods to fix it. Also, learn about an advanced Access repair tool to repair the corrupted database file quickly and easily.

Free Download for Windows

Contents

  • Common Scenarios of MS Access Runtime Error 3146
  • Causes behind ODBC Call Failed Error in Access
  • Troubleshooting Methods to Resolve ODBC Call Failed Error in Access
  • To Conclude

Many Access users use ODBC protocol to connect data sources to MS Access. The data source contains files, worksheets, and database connection-related information. Connecting data source to Access requires defining the data source name (DSN) and ODBC driver. Access does not have built-in drivers to establish connection with other external databases, such as Oracle, SQL Server, MySQL Server, etc. For this, you require to install appropriate ODBC driver, compatible with your system.

If there is any issue with the ODBC driver or the ODBC connection fails to connect to a data source, then you can encounter the runtime error 3146 “ODBC Call Failed” in MS Access. The error can also occur when you define the data source directly to the ODBC driver manager through a VBA code. It usually happens when you use an incorrect query to pass the connection string or if there are other code problems.  

Common Scenarios of MS Access Runtime Error 3146

Here are some common scenarios where you can come across the “ODBC Call Failed” error:

  • When trying to open a table in the Access database to edit a record set.
  • When trying to connect Microsoft Access to the SQL Server using the ODBC driver.
  • When trying to open the Access database file on a shared network.
  • When trying to import SQL Server data into Microsoft Access using an ODBC connection.

Causes behind ODBC Call Failed Error in Access

The ODBC Call Failed error indicates an issue with the ODBC connection in the Access database. Apart from this, there are multiple reasons that may lead to such an issue. Some of them are:

  • The ODBC driver (ODBC data source administrator) is not compatible with the Access version
  • Corrupt Data Source file
  • You do not have necessary permissions to access the data source
  • Issue with the network connection
  • Incorrect data source configuration in the ODBC data source administrator
  • Access database file is corrupted
  • ODBC driver is not installed correctly
  • Wrong paths to the shared network can cause inconsistencies
  • Disabled Connection Pooling option
  • Windows Firewall is blocking the connection between MS Access and the external data source
  • Not defined or incorrect DSN (Data Source Name)
  • Incorrect ODBC credentials

Troubleshooting Methods to Resolve ODBC Call Failed Error in Access

You can receive the ODBC connection failed error if your Access database has insufficient permissions to use the ODBC protocol. So, first ensure that the desired database has all the necessary permissions to perform certain actions using the ODBC connection. If this is not the case, then try the following methods to fix the error.

Method 1: Check the VBA Code

The MS Access runtime error 3146 – ODBC call failed can occur if there is an issue with the VBA code you’re using to interact with the external data source using ODBC connection. It usually appears while defining a data source name (DSN) using a connection string. It can occur if the connection string in the VBA code fails to match the configuration of the external data source. To fix this, review and correct the issues in the code. Here are the steps:

  • Open the Access database, go to Database Tools and then click the Visual Basic tab.

Selecting Visual Basic under Database Tools

  • The Microsoft Visual Basic for Application editor is displayed.

Microsoft Visual Basic for Application editor code under Form_Purchases

Check the VBA code and do the following to troubleshoot the issue in the code:

  • Make sure you are using the correct connection string syntax.
  • Verify the name of the objects.
  • Check all the syntaxes, references, and queries in the code.

Method 2: Check ODBC Credentials

The Access ODBC call failed error can occur if Access fails to authenticate the DSN (Data Source Name). It happens if the ODBC connection fails due to incorrect or mismatched credentials. You can check and change the ODBC credentials to fix the issue. Here are the steps:

  • Open the Access database, click External Data, and then select ODBC Database.

ODBC Database under the External Data

  • The Get External Data – ODBC Database window is displayed. Click “Link to the data source by creating a linked table.”

Selecting the source and destination of data via Get External Data

  • In the Select Data Source window, select the Machine Data Source option and click on the New option.
  • In the Create New Data Source dialog box, click SQL Server and then select Next.

Creating new data source from SQL server

  • Then, click on the Finish option.

Selecting SQL server driver and finishing the data source creation

  • In Create a New Data Source to SQL Server window, verify the login credentials and then select Next.

Adding login information to connect with password

Verify if the error 3146 is fixed. If not, then check the ODBC Connection Database Setup.

Method 3: Verify ODBC Connection Database Setup

The Access ODBC call failed error can also occur if the ODBC connection setup is not configured correctly or if there are below issues:

  • You are using an incompatible ODBC driver.
  • DSN file is corrupted.
  • DSN is not properly configured correctly.
  • DSN is not referenced to the correct database (when using a connection string in VBA).

To fix this, install a compatible ODBC driver and recreate the DSN file.

Method 4: Verify Network Configuration

The ODBC call failed error can occur if there is a connection failure between MS Access and the external data source when using ODBC protocol. It usually occurs due to incorrect Firewall settings and Antivirus software or network settings. You can temporarily disable the Firewall and Antivirus to troubleshoot the issue. You can also check the active TCP connection and other network-related information using Command Prompt. Here are the steps:

  • In the system’s search field, type cmd and press Enter.
  • In the Command Prompt window, type netstat –n –a.

 Prompting command and typing netstat –n –a.

It will display network information, including IP address, port numbers, TCP, fully qualified domain names, listening ports, protocols, and more. Check the network information. If you found any issue, reconfigure the network configuration settings or contact your IT team.

Method 5: Enable Pooling Settings in the ODBC Data Source Administrator

The “Connection Pooling” option in the ODBC driver ensures database connections. If the pooling option is disabled, it can result in the “ODBC connection failed” error. You can open the ODBC data source administrator to check and enable the Connection Pooling. Follow the below steps to do so:

  • Open Control Panel.
  • In the Control Panel window, double-click on the Administrative Tools option.

Selecting Administrative Tools from Control Panel

  • In the Administrative Tools window, find ODBC Data Source (64-bit) and double-click on it.

finding  odbc data source from administrative tools window

  • The ODBC Data Source Administrator window appears. Go to the Connection Pooling option and select the “Enable ODBC connection Pooling PerfMon counters for troubleshooting” option. 

Adding the Connection Pooling and selecting Driver with its Pool timeout

  • Click OK.

In ODBC Data Source Administrator window, you can also check settings under the Driver, User DSN, System DSN, and Drivers tabs and ensure they’re correct.

Selecting and adding File Stream From ODBC data Source

Method 6: Use Tracing Logs

The ODBC tracing option provides a detailed log of the traces of the communication between MS Access and other external data sources. If the Tracing option is enabled in the driver, you can use these detailed logs to identify the cause of the ODBC connection issue and troubleshoot the same. You can open the ODBC Data Source Administrator and click on the Tracing option to view the log of the calls to ODBC driver.

Method 7: Repair your Access Database

The Access ODBC connection failed error can also occur due to corrupted database objects, queries, tables, or indexes. The corruption in the Access database file can create inconsistencies and affect the ODBC connection. You can repair your Access database using the Access inbuilt utility – Compact and Repair. Here are the steps to use this utility:

  • Open the desired Access database.
  • Navigate to the File and then click the Info option.
  • Click on the Compact & Repair database option.
  • Go to the database’s original location to view the repaired database.

If, due to any reason, the Compact and Repair utility fails to repair the database file, then opt for a professional Access repair tool. Stellar Repair for Access is a powerful tool that can fix severely damaged or corrupted Access database (.ACCDB/.MDB) files. You can download the software’s demo version that can allow you to scan the corrupt file and preview all the recoverable data. The tool is compatible with all Windows editions, including Windows 11.

To Conclude

You can experience the runtime error 3146 in MS Access, if there is ODBC protocol connection failure. Try the troubleshooting methods mentioned in the post to fix the issue. If the issue has occurred due to corrupted database, then you can use Stellar Repair for Access to repair the database with 100% integrity. The tool is compatible with all MS Access versions, including MS Access 2019. Download the software’s demo version to check its functionality before purchasing.

About The Author

Monika Dadool

Monika Dadool is a Technical content writer at Stellar who writes about QuickBooks, Sage50, MySQL Database, Active Directory, e-mail recovery, Microsoft365, Pattern Recognition, and Machine learning. She loves researching, exploring new technology, and Developing engaging technical blogs that help organizations or Database Administrators fix multiple issues. When she isn’t creating content, she is busy on social media platforms, watching web series, reading books, and searching for food recipes.

My client is using Access as a front end to a SQL Server database. They recently started getting ODBC — 3146 errors from time to time when running some reports. From what I can tell, this is just a generic ODBC call failed error.

I’ve tried sticking some error handling in the VB script that is launching the reports, but I am not having any luck getting extra error information.

Code looks a bit like this.

Public Function RunReports()
  On Error GoTo MyErrorTrap

  DoCmd.OpenReport "blah", acViewPreview
  DoCmd.Close

  DoCmd.OpenReport "foo", acViewPreview
  DoCmd.Close

Exit_function:
  Exit Function

MyErrorTrap:
  Dim errX As DAO.Error
  Dim MyError As Error
  If Errors.Count > 1   'This always seems to be 0, so no help
    For Each errX In DAO.Errors  'These are empty even if dont check for Errors.Count
      Debug.Print "ODBC Error"
      Debug.Print errX.Number
      Debug.Print errX.Description
    Next errX
  Else
    Debug.Print "VBA Error"
    Debug.Print Err.Number
    Debug.Print Err.Description
  End If

  'Also have tried checking DBEngine.Errors, but this is empty too

End Function

I’ve also enabled tracing on the ODBC side, but that has bogged things down way too much, and I am so far unable to recreate the ODBC error.

I am completely open for suggestions on how to diagnose this.

Понравилась статья? Поделить с друзьями:
  • Runtime error 1004 общая ошибка odbc
  • Runtime broker ошибка файловой системы
  • Runtime broker ошибка приложения
  • Runas ошибка 1058
  • Run time error 1004 excel ошибка