Error failed to open file error 2 mysql

Learn how to fix 'Failed to open file error 2' in MySQL

When you try to run an SQL file using mysql command line program, you may encounter an error saying Failed to open file error 2.

The following example tries to run the source command and execute the query.sql file:

mysql> source query.sql
ERROR: 
Failed to open file 'query.sql', error: 2

The code error 2 means that MySQL can’t find the .sql file that you want to execute.

To solve this error, you need to provide the absolute path to your file location.

You can find the absolute path of your file by opening the terminal in the directory or folder where your SQL file is located and run the pwd command.

For example, here’s the absolute path to the directory where I save the query.sql file:

$ pwd
/Users/nsebhastian/Desktop/SQL-files

Now I just need to add the path to the file when I issue the source command:

mysql> source /Users/nsebhastian/Desktop/SQL-files/query.sql

Please note that you need to use forward slashes (/) to separate your path sections. Using back slashes () may cause the same error.

Here’s an example:

mysql> source UsersnsebhastianDesktopSQL-filesquery.sql
ERROR: 
Failed to open file 'UsersnsebhastianDesktopSQL-filesquery.sql', error: 2

Even though the path is correct, MySQL expects a Unix-style path with forward slashes.

You should now be able to execute the SQL file. There are some other causes for error 2 in MySQL, so let’s take a look at that next.

Error 2 because of < or > symbols

Another thing that could cause the error is that you’re adding the greater than > or less than < symbol in front of the file path as shown below:

mysql> source < /Users/nsebhastian/Desktop/SQL-files/query.sql
ERROR: 
Failed to open file '< /Users/nsebhastian/Desktop/SQL-files/query.sql', 
error: 2

The greater than or less than symbol is commonly used to dump MySQL data to an SQL file or execute a script from the terminal without connecting to MySQL server.

You need to remove the symbol to execute the source command without error.

Error 2 because of semicolon when using . command

The . command is an alias of the source command that you can use to run an SQL file.

I don’t know if it’s a MySQL bug, but when you run the . command with a semicolon ; at the end of the file path, you’ll get the error 2 response.

Take a look at the following example:

mysql> . /Users/nsebhastian/Desktop/SQL-files/query.sql;
ERROR: 
Failed to open file '/Users/nsebhastian/Desktop/SQL-files/query.sql;', 
error: 2

But the same error won’t happen when you use the source command:

mysql> source /Users/nsebhastian/Desktop/SQL-files/query.sql;
...
# result
...
7 rows in set (0.00 sec)

To solve this issue, you need to omit the semicolon when you’re using the . command.

And that’s how you fix the MySQL failed to open file error 2 issue.

Just keep in mind that the error is because MySQL can’t find the file you want to execute.

You probably need to check the path you passed into the source command and see if there’s any typo that causes the error.

I recently had to restore a MySQL backup. It had been a while since I used MySQL, having switched to Postgresql sometime back. First thing I noticed was the lack of a GUI admin tool that PG spoils you with. Making matters worse, the command line tool isn’t even added to your path; you can’t just run “mysql” like you can in a Unix shell, much less use the redirect shortcut. And I was getting errors.

Here’s what you need to do to restore a MySQL backup on Windows:

  1. Run the command line tool from the start menu
  2. Open your backup file in a text editor. Does it start with a command to create or “use” the database? If not
    1. Create it, if necessary
    2. Type “use database” filling in your DB name
  3. Type “source path-to-SQL-file“. BUT, you must follow these rules:
    1. Use the full source command, not the . shortcut
    2. Have no spaces in your path. I copied mine to a root of a drive. Note that spaces in the file name is OK, just not the path.
    3. Do not quote the file name, even if it has spaces. This gave error 22.
    4. Use forward slashes in the path, e.g., C:/path/to/filename.sql. Otherwise you’ll get error 2.
    5. Do not end with a semicolon.

Follow all those rules and it should work fine.

Содержание

  1. MySQL — How to solve ‘Failed to open file error 2’
  2. Error 2 because of symbols
  3. Error 2 because of semicolon when using . command
  4. Level up your programming skills
  5. About
  6. MySQL Failed to open file – error 2 and 22 on Windows
  7. Share this:
  8. 30 Comments
  9. Consent to the use of Personal Data and Cookies
  10. Solution to SOURCE Error 2 with MySQL
  11. Writing file paths
  12. RTFM.WIKI
  13. Инструменты пользователя
  14. Инструменты сайта
  15. Содержание
  16. MySQL — коллекция ошибок и фиксов
  17. Ошибки
  18. Foreign key / Внешние ключи / Ошибка #1217
  19. Run ‘systemctl daemon-reload’ to reload units
  20. Can’t init tc log
  21. MySQL “Got an error reading communication packet” errors
  22. #1524 — Plugin ‘unix_socket’ is not loaded
  23. Can’t create a new thread (errno 11)
  24. #1698 — Access denied for user ‘root’@’localhost’
  25. mysqldump: Couldn’t execute ‘show events’
  26. #1214 — The used table type doesn’t support FULLTEXT indexes
  27. Waiting for table metadata lock
  28. No directory, logging in with HOME=/
  29. Can’t create thread to kill server (errno= 11)
  30. Can’t create a new thread (errno 11)
  31. unknown variable ‘default-tmp-storage-engine=MyISAM’
  32. Host ‘a.b.c.d’ is blocked because of many connection errors; unblock with ‘myscladmin flush-hosts’
  33. Fatal error: Uncaught exception ‘Exception’ with message ‘Error: Can’t open file: ‘./ocr/oc_product.frm’ (errno: 24)
  34. InnoDB: mmap(137363456 bytes) failed; errno 12
  35. Правильный UTF-8
  36. #1146 — Table ‘data_dictionary.CHARACTER_SETS’ doesn’t exist
  37. /usr/sbin/mysqld: Error on realpath() on ‘/var/lib/mysql-files’ (Error 2)
  38. ‘ERROR 1214 (HY000) at line 784: The used table type doesn’t support FULLTEXT indexes ‘
  39. Got an error from unknown thread, /builddir/build/BUILD /storage/myisam/mi_write.c:226
  40. mysqldump: Got error: (Errcode: 24) when using LOCK TABLES
  41. Error Number: 1364
  42. #1030 — Got error -1 from storage engine
  43. error: ‘Access denied for user ‘debian-sys-maint’@’localhost’ (using password: YES)’
  44. open-files-limit в MariaDB
  45. Unable to lock ./ibdata1, error: 11
  46. unknown option ‘—skip-locking’
  47. RTFM.WIKI
  48. Инструменты пользователя
  49. Инструменты сайта
  50. Содержание
  51. MySQL — коллекция ошибок и фиксов
  52. Ошибки
  53. Foreign key / Внешние ключи / Ошибка #1217
  54. Run ‘systemctl daemon-reload’ to reload units
  55. Can’t init tc log
  56. MySQL “Got an error reading communication packet” errors
  57. #1524 — Plugin ‘unix_socket’ is not loaded
  58. Can’t create a new thread (errno 11)
  59. #1698 — Access denied for user ‘root’@’localhost’
  60. mysqldump: Couldn’t execute ‘show events’
  61. #1214 — The used table type doesn’t support FULLTEXT indexes
  62. Waiting for table metadata lock
  63. No directory, logging in with HOME=/
  64. Can’t create thread to kill server (errno= 11)
  65. Can’t create a new thread (errno 11)
  66. unknown variable ‘default-tmp-storage-engine=MyISAM’
  67. Host ‘a.b.c.d’ is blocked because of many connection errors; unblock with ‘myscladmin flush-hosts’
  68. Fatal error: Uncaught exception ‘Exception’ with message ‘Error: Can’t open file: ‘./ocr/oc_product.frm’ (errno: 24)
  69. InnoDB: mmap(137363456 bytes) failed; errno 12
  70. Правильный UTF-8
  71. #1146 — Table ‘data_dictionary.CHARACTER_SETS’ doesn’t exist
  72. /usr/sbin/mysqld: Error on realpath() on ‘/var/lib/mysql-files’ (Error 2)
  73. ‘ERROR 1214 (HY000) at line 784: The used table type doesn’t support FULLTEXT indexes ‘
  74. Got an error from unknown thread, /builddir/build/BUILD /storage/myisam/mi_write.c:226
  75. mysqldump: Got error: (Errcode: 24) when using LOCK TABLES
  76. Error Number: 1364
  77. #1030 — Got error -1 from storage engine
  78. error: ‘Access denied for user ‘debian-sys-maint’@’localhost’ (using password: YES)’
  79. open-files-limit в MariaDB
  80. Unable to lock ./ibdata1, error: 11
  81. unknown option ‘—skip-locking’

MySQL — How to solve ‘Failed to open file error 2’

Posted on Nov 03, 2021

Learn how to fix ‘Failed to open file error 2’ in MySQL

When you try to run an SQL file using mysql command line program, you may encounter an error saying Failed to open file error 2 .

The following example tries to run the source command and execute the query.sql file:

The code error 2 means that MySQL can’t find the .sql file that you want to execute.

To solve this error, you need to provide the absolute path to your file location.

You can find the absolute path of your file by opening the terminal in the directory or folder where your SQL file is located and run the pwd command.

For example, here’s the absolute path to the directory where I save the query.sql file:

Now I just need to add the path to the file when I issue the source command:

Please note that you need to use forward slashes ( / ) to separate your path sections. Using back slashes ( ) may cause the same error.

Here’s an example:

Even though the path is correct, MySQL expects a Unix-style path with forward slashes.

You should now be able to execute the SQL file. There are some other causes for error 2 in MySQL, so let’s take a look at that next.

Error 2 because of symbols

Another thing that could cause the error is that you’re adding the greater than > or less than symbol in front of the file path as shown below:

The greater than or less than symbol is commonly used to dump MySQL data to an SQL file or execute a script from the terminal without connecting to MySQL server.

You need to remove the symbol to execute the source command without error.

Error 2 because of semicolon when using . command

The . command is an alias of the source command that you can use to run an SQL file.

I don’t know if it’s a MySQL bug, but when you run the . command with a semicolon ; at the end of the file path, you’ll get the error 2 response.

Take a look at the following example:

But the same error won’t happen when you use the source command:

To solve this issue, you need to omit the semicolon when you’re using the . command.

And that’s how you fix the MySQL failed to open file error 2 issue.

Just keep in mind that the error is because MySQL can’t find the file you want to execute.

You probably need to check the path you passed into the source command and see if there’s any typo that causes the error.

Level up your programming skills

I’m sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Nathan Sebhastian is a software engineer with a passion for writing tech tutorials.
Learn JavaScript and other web development technology concepts through easy-to-understand explanations written in plain English.

Источник

MySQL Failed to open file – error 2 and 22 on Windows

I recently had to restore a MySQL backup. It had been a while since I used MySQL, having switched to Postgresql sometime back. First thing I noticed was the lack of a GUI admin tool that PG spoils you with. Making matters worse, the command line tool isn’t even added to your path; you can’t just run “ mysql ” like you can in a Unix shell, much less use the redirect shortcut. And I was getting errors.

Here’s what you need to do to restore a MySQL backup on Windows:

  1. Run the command line tool from the start menu
  2. Open your backup file in a text editor. Does it start with a command to create or “use” the database? If not
    1. Create it, if necessary
    2. Type “use database” filling in your DB name
  3. Type “source path-to-SQL-file“. BUT, you must follow these rules:
    1. Use the full source command, not the . shortcut
    2. Have no spaces in your path. I copied mine to a root of a drive. Note that spaces in the file name is OK, just not the path.
    3. Do not quote the file name, even if it has spaces. This gave error 22.
    4. Use forward slashes in the path, e.g., C:/path/to/filename.sql. Otherwise you’ll get error 2.
    5. Do not end with a semicolon.

Follow all those rules and it should work fine.

Thanks so much for this info. You where a savior to me this night. In my work for a project for this my site,Code Messiah, I run into an issue when I have to migrate some project in .net to MySQL. Thanks you for this guide. Its short but henvy

Thank you so much

Hi, just a heads up;
You can use backslashes but you’ll have to escape them (“\”); and you can use semicolons, it worked as well. However I wouldn’t have figured out that the problem was the spaces in the path, that’s the main issue! So thanks for the article!

Thank you very much, it works!

This was quite helpful. Thanks for the tips.

Источник

Consent to the use of Personal Data and Cookies

This website needs your consent to use cookies in order to customize ads and content.

If you give us your consent, data may be shared with Google.

Solution to SOURCE Error 2 with MySQL

The error happens when importing database backups using the SOURCE command, either because you got the path wrong, or because you used the command incorrectly.

Edited: 2021-01-26 15:34

This is just a quick reminder to those having problems backing up- and importing MySQL databases. Often when I try to import a database using the SOURCE command I will get a SOURCE error 2 message.

The error simply means that we have gotten the file path wrong. However, in my case, it was because I used a less than sign between the SOURCE and the file name.

The reason for my mistake is that I use a greater than sign when backing up a database using mysqldump, and sometimes I mess up because the same logic does not apply when importing. Hopefully I will remember it now.

Writing file paths

To understand how to write the file system paths, read this article: Absolute and Relative Paths

Basically, when making backups, you can either write an absolute path for the destination file, beginning with a forward slash «/», or you can use a relative path. Simply writing the file name of the destination file will write the file in the current directory.

You can use the CD command to navigate to the desired location, if you feel more comfortable doing that.

Источник

RTFM.WIKI

Ordnung muß sein. Ordnung über alles (18+)

Инструменты пользователя

Инструменты сайта

Содержание

MySQL — коллекция ошибок и фиксов

Ошибки

Foreign key / Внешние ключи / Ошибка #1217

Теория в другом месте. Только фикс.

Текст ошибки может быть разным

В mysql cli отключаем проверку внешних ключей, делаем нужный запрос, включаем обратно.

можно ещё проще сделать

Run ‘systemctl daemon-reload’ to reload units

Warning: The unit file, source configuration file or drop-ins of mariadb.service changed on disk. Run ‘systemctl daemon-reload’ to reload units.

Can’t init tc log

MySQL “Got an error reading communication packet” errors

#1524 — Plugin ‘unix_socket’ is not loaded

Can’t create a new thread (errno 11)

Ошибка Can’t create a new thread (errno 11); if you are not out of available memory, you can consult the manual for a possible OS -dependent bug

Лимиты установленные для MySQL в файле /etc/security/limits.conf будут переопределены файлом /etc/security/limits.d/90-nproc.conf . Поэтому задавать лимиты нужно в 90-nproc.conf или создать отдельный файл 91-mysql.conf

#1698 — Access denied for user ‘root’@’localhost’

Не работает phpmyadmin под root’ом. Для MySQL 127.0.0.1 и localhost это разные хосты.

Добавляем отдельного пользователя для администрирования

что-то там с sudo и unix_socket, не разбирался пока, но вариант рабочий.

mysqldump: Couldn’t execute ‘show events’

Ошибка mysqldump: Couldn’t execute ‘show events’: Cannot proceed because system tables used by Event Scheduler were found damaged at server start после перехода на MariaDB с MySQL 56 на cPanel сервере

mysql_upgrade по рекомендациям тоже не работает с ошибкой mysqldump: Got error: 1102: Incorrect database name ‘#mysql50#.config’» when selecting the database

И мне помог не cPanel, а Plesk

В /var/lib/mysql/ был каталог с точкой в имени.

Чтобы его найти выполним команду

Решение

Удалить/перенести каталог в другой место, выполнить mysql_upgrade.

#1214 — The used table type doesn’t support FULLTEXT indexes

Индексы FULLTEXT поддерживаются в таблицах InnoDB только начиная с MYSQL 5.6, поэтому попробуйте обновить MYSQL и после этого изменить команду таблицы

Waiting for table metadata lock

No directory, logging in with HOME=/

Подобная ошибка была в Debian с репозиторием dotdeb.

Надо поправить /etc/passwd

Должно быть так

Can’t create thread to kill server (errno= 11)

Скорее всего на сервере недостаточно памяти для выбранных настроек в my.cnf .

Т.е. key_buffer_size + (read_buffer_size + sort_buffer_size)*max_connections в итоге получается больше чем RAM на сервере.

Решение — уменьшить max_connections и другие параметры исходя из доступных ресурсов.

Can’t create a new thread (errno 11)

Ошибка похожа на Can’t create thread to kill server и также связана с лимитами.

В данном случае нужно увеличить количество открытых файлов и количество процессов ( nofile и nproc ).

По-умолчанию open files равен 1024.

Проверим, чтобы удостовериться

Добавляем в файл /etc/security/limits.conf

Либо устанавливаем лимит только для mysql

Нашёл рекомендацию добавить лимиты в отдельный файл 99-mysql.conf в каталоге /etc/security/limits.d/

unknown variable ‘default-tmp-storage-engine=MyISAM’

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

default-tmp-storage-engine появился только в MySQL 5.6 и если использовать опцию в версии 5.5, то MySQL не запустится.

Host ‘a.b.c.d’ is blocked because of many connection errors; unblock with ‘myscladmin flush-hosts’

Ошибка возникает после 10 (по-умолчанию) неудачных соединений с базой.

Fatal error: Uncaught exception ‘Exception’ with message ‘Error: Can’t open file: ‘./ocr/oc_product.frm’ (errno: 24)

В логе mariadb.log нечто подобное

Решение — см. запись ниже open-files-limit в MariaDB

Текущее использование открытых файлов можно посмотреть так:

InnoDB: mmap(137363456 bytes) failed; errno 12

Решение — уменьшить innodb_buffer_pool_size или добавить RAM.

Правильный UTF-8

а потом трахбах и deprecated

#1146 — Table ‘data_dictionary.CHARACTER_SETS’ doesn’t exist

И опять убунта. Что за чудо система. Не даёт скучать. Сиди чини её нескончаемые баги. Впрочем ничего нового.

И всё начинает работать. До следующего адового бага. Продакшен реди итиху мать.

/usr/sbin/mysqld: Error on realpath() on ‘/var/lib/mysql-files’ (Error 2)

Баг после апгрейда встретился только в Ubuntu

ЕМНИП нужно просто создать каталог /var/lib/mysql-files

‘ERROR 1214 (HY000) at line 784: The used table type doesn’t support FULLTEXT indexes ‘

FULLTEXT INDEX раньше работал только с MyISAM. С версии 5.6 доступен в InnoDB.

Так что либо апгрейд либо ALTER TABLE `yourtable` ENGINE = MyISAM;

Got an error from unknown thread, /builddir/build/BUILD /storage/myisam/mi_write.c:226

Также в логах может быть что-то вроде Incorrect key file for table ‘xyz.MYI’; try to repair it

Казалось бы следует сделать mysqlrepair –auto-repair . Но обычно это не помогает.

Скорее всего нет инодов или кончилось место или недоступен tmpdir в mysql.

Проверяем df -i и df -h . Также проверяем значение tmpdir в my.cnf

mysqldump: Got error: (Errcode: 24) when using LOCK TABLES

Узнал о крутой утилите perror. По коду ошибки покажет, что не так.

Ну и по ошибке выше — попробуйте добавить опцию —single-transaction к mysqldump

Error Number: 1364

Через tcpdump выловил ошибку в php-fpm

Виной всему старый код и новый (5.7) MySQL.

Быстрый фикс — выключить так называемый strict mode

Для этого нужно добавить в my.cnf

Можно также вынести в отдельный файл /etc/mysql/conf.d/disable_strict_mode.cnf

Проверить sql_mode

#1030 — Got error -1 from storage engine

При попытке выполнить SQL запрос в phpmyadmin получаем ошибку #1030 — Got error -1 from storage engine

Вероятно включен innodb_force_recovery в файле my.cnf .

Проверяем логи. Если есть нечто подобное

то значит так оно и есть. Выключаем innodb_force_recovery и всё снова работает.

error: ‘Access denied for user ‘debian-sys-maint’@’localhost’ (using password: YES)’

Смотрим пароль пользователя debian-sys-maint в файле /etc/mysql/debian.cnf

Выполняем 2 SQL запроса, чтобы вернуть гражданину debian-sys-maint его привилегии

Перезапускаем MySQL сервер

open-files-limit в MariaDB

Systemd самостоятельно контролирует, сколько файлов служба (в нашем случае mariadb-server) может открыть, независимо от того, что вы настроили в /etc/my.cnf или в /etc/security/limits.conf .

И вносим следующие правки

Данные новшества однако документированы. Так что надо просто внимательнее читать release notes и changelog.

Unable to lock ./ibdata1, error: 11

Решение в сети, которое якобы некоторым помогает

увы не помогает.

Бытует мнение, что виной всему Apparmor т.к. нигде кроме Ubuntu ошибка эта не встречалась

Можно попробовать добавить в /etc/apparmor.d/usr.sbin.mysqld

надо проверить

unknown option ‘—skip-locking’

Опцию –skip-locking убрали в MySQL 5.5.

Решение: заменить skip-locking на skip-external-locking

Источник

RTFM.WIKI

Ordnung muß sein. Ordnung über alles (18+)

Инструменты пользователя

Инструменты сайта

Содержание

MySQL — коллекция ошибок и фиксов

Ошибки

Foreign key / Внешние ключи / Ошибка #1217

Теория в другом месте. Только фикс.

Текст ошибки может быть разным

В mysql cli отключаем проверку внешних ключей, делаем нужный запрос, включаем обратно.

можно ещё проще сделать

Run ‘systemctl daemon-reload’ to reload units

Warning: The unit file, source configuration file or drop-ins of mariadb.service changed on disk. Run ‘systemctl daemon-reload’ to reload units.

Can’t init tc log

MySQL “Got an error reading communication packet” errors

#1524 — Plugin ‘unix_socket’ is not loaded

Can’t create a new thread (errno 11)

Ошибка Can’t create a new thread (errno 11); if you are not out of available memory, you can consult the manual for a possible OS -dependent bug

Лимиты установленные для MySQL в файле /etc/security/limits.conf будут переопределены файлом /etc/security/limits.d/90-nproc.conf . Поэтому задавать лимиты нужно в 90-nproc.conf или создать отдельный файл 91-mysql.conf

#1698 — Access denied for user ‘root’@’localhost’

Не работает phpmyadmin под root’ом. Для MySQL 127.0.0.1 и localhost это разные хосты.

Добавляем отдельного пользователя для администрирования

что-то там с sudo и unix_socket, не разбирался пока, но вариант рабочий.

mysqldump: Couldn’t execute ‘show events’

Ошибка mysqldump: Couldn’t execute ‘show events’: Cannot proceed because system tables used by Event Scheduler were found damaged at server start после перехода на MariaDB с MySQL 56 на cPanel сервере

mysql_upgrade по рекомендациям тоже не работает с ошибкой mysqldump: Got error: 1102: Incorrect database name ‘#mysql50#.config’» when selecting the database

И мне помог не cPanel, а Plesk

В /var/lib/mysql/ был каталог с точкой в имени.

Чтобы его найти выполним команду

Решение

Удалить/перенести каталог в другой место, выполнить mysql_upgrade.

#1214 — The used table type doesn’t support FULLTEXT indexes

Индексы FULLTEXT поддерживаются в таблицах InnoDB только начиная с MYSQL 5.6, поэтому попробуйте обновить MYSQL и после этого изменить команду таблицы

Waiting for table metadata lock

No directory, logging in with HOME=/

Подобная ошибка была в Debian с репозиторием dotdeb.

Надо поправить /etc/passwd

Должно быть так

Can’t create thread to kill server (errno= 11)

Скорее всего на сервере недостаточно памяти для выбранных настроек в my.cnf .

Т.е. key_buffer_size + (read_buffer_size + sort_buffer_size)*max_connections в итоге получается больше чем RAM на сервере.

Решение — уменьшить max_connections и другие параметры исходя из доступных ресурсов.

Can’t create a new thread (errno 11)

Ошибка похожа на Can’t create thread to kill server и также связана с лимитами.

В данном случае нужно увеличить количество открытых файлов и количество процессов ( nofile и nproc ).

По-умолчанию open files равен 1024.

Проверим, чтобы удостовериться

Добавляем в файл /etc/security/limits.conf

Либо устанавливаем лимит только для mysql

Нашёл рекомендацию добавить лимиты в отдельный файл 99-mysql.conf в каталоге /etc/security/limits.d/

unknown variable ‘default-tmp-storage-engine=MyISAM’

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

default-tmp-storage-engine появился только в MySQL 5.6 и если использовать опцию в версии 5.5, то MySQL не запустится.

Host ‘a.b.c.d’ is blocked because of many connection errors; unblock with ‘myscladmin flush-hosts’

Ошибка возникает после 10 (по-умолчанию) неудачных соединений с базой.

Fatal error: Uncaught exception ‘Exception’ with message ‘Error: Can’t open file: ‘./ocr/oc_product.frm’ (errno: 24)

В логе mariadb.log нечто подобное

Решение — см. запись ниже open-files-limit в MariaDB

Текущее использование открытых файлов можно посмотреть так:

InnoDB: mmap(137363456 bytes) failed; errno 12

Решение — уменьшить innodb_buffer_pool_size или добавить RAM.

Правильный UTF-8

а потом трахбах и deprecated

#1146 — Table ‘data_dictionary.CHARACTER_SETS’ doesn’t exist

И опять убунта. Что за чудо система. Не даёт скучать. Сиди чини её нескончаемые баги. Впрочем ничего нового.

И всё начинает работать. До следующего адового бага. Продакшен реди итиху мать.

/usr/sbin/mysqld: Error on realpath() on ‘/var/lib/mysql-files’ (Error 2)

Баг после апгрейда встретился только в Ubuntu

ЕМНИП нужно просто создать каталог /var/lib/mysql-files

‘ERROR 1214 (HY000) at line 784: The used table type doesn’t support FULLTEXT indexes ‘

FULLTEXT INDEX раньше работал только с MyISAM. С версии 5.6 доступен в InnoDB.

Так что либо апгрейд либо ALTER TABLE `yourtable` ENGINE = MyISAM;

Got an error from unknown thread, /builddir/build/BUILD /storage/myisam/mi_write.c:226

Также в логах может быть что-то вроде Incorrect key file for table ‘xyz.MYI’; try to repair it

Казалось бы следует сделать mysqlrepair –auto-repair . Но обычно это не помогает.

Скорее всего нет инодов или кончилось место или недоступен tmpdir в mysql.

Проверяем df -i и df -h . Также проверяем значение tmpdir в my.cnf

mysqldump: Got error: (Errcode: 24) when using LOCK TABLES

Узнал о крутой утилите perror. По коду ошибки покажет, что не так.

Ну и по ошибке выше — попробуйте добавить опцию —single-transaction к mysqldump

Error Number: 1364

Через tcpdump выловил ошибку в php-fpm

Виной всему старый код и новый (5.7) MySQL.

Быстрый фикс — выключить так называемый strict mode

Для этого нужно добавить в my.cnf

Можно также вынести в отдельный файл /etc/mysql/conf.d/disable_strict_mode.cnf

Проверить sql_mode

#1030 — Got error -1 from storage engine

При попытке выполнить SQL запрос в phpmyadmin получаем ошибку #1030 — Got error -1 from storage engine

Вероятно включен innodb_force_recovery в файле my.cnf .

Проверяем логи. Если есть нечто подобное

то значит так оно и есть. Выключаем innodb_force_recovery и всё снова работает.

error: ‘Access denied for user ‘debian-sys-maint’@’localhost’ (using password: YES)’

Смотрим пароль пользователя debian-sys-maint в файле /etc/mysql/debian.cnf

Выполняем 2 SQL запроса, чтобы вернуть гражданину debian-sys-maint его привилегии

Перезапускаем MySQL сервер

open-files-limit в MariaDB

Systemd самостоятельно контролирует, сколько файлов служба (в нашем случае mariadb-server) может открыть, независимо от того, что вы настроили в /etc/my.cnf или в /etc/security/limits.conf .

И вносим следующие правки

Данные новшества однако документированы. Так что надо просто внимательнее читать release notes и changelog.

Unable to lock ./ibdata1, error: 11

Решение в сети, которое якобы некоторым помогает

увы не помогает.

Бытует мнение, что виной всему Apparmor т.к. нигде кроме Ubuntu ошибка эта не встречалась

Можно попробовать добавить в /etc/apparmor.d/usr.sbin.mysqld

надо проверить

unknown option ‘—skip-locking’

Опцию –skip-locking убрали в MySQL 5.5.

Решение: заменить skip-locking на skip-external-locking

Источник

The error happens when importing database backups using the SOURCE command, either because you got the path wrong, or because you used the command incorrectly.

12394 views

d

By. Jacob

Edited: 2021-01-26 15:34

This is just a quick reminder to those having problems backing up- and importing MySQL databases. Often when I try to import a database using the SOURCE command I will get a SOURCE error 2 message.

The error simply means that we have gotten the file path wrong. However, in my case, it was because I used a less than sign between the SOURCE and the file name.

The reason for my mistake is that I use a greater than sign when backing up a database using mysqldump, and sometimes I mess up because the same logic does not apply when importing. Hopefully I will remember it now.

mysql> SOURCE < /home/username/database_backup.sql

RROR:
Failed to open file ‘< /home/username/database_backup.sql’, error: 2

If you have made the same mistake, simply remove the less than sign from your statement. The SQL statement should look like this:

SOURCE /home/UserName/some_sql_file.sql

The problem can also be that you miss typed the path for the .sql file, though I suppose this is unlikely if you know what you are doing, but be sure to double check this as well.

Alternatively, you can also import databases using mysql in a terminal, in which case you will be using the less than sign:

mysql database_name < database_name.sql

To create a .sql backup of a database, use mysqldump:

mysqldump database_name > database_name.sql

Writing file paths

To understand how to write the file system paths, read this article: Absolute and Relative Paths

Basically, when making backups, you can either write an absolute path for the destination file, beginning with a forward slash «/», or you can use a relative path. Simply writing the file name of the destination file will write the file in the current directory.

You can use the CD command to navigate to the desired location, if you feel more comfortable doing that.

You need to make sure the location is writable when creating a backup. Personally I prefer just outputting to /home/MyUser/databases/name-of-output-file.sql, since I know this will be writable.

  1. How to configure phpMyAdmin with automatic login by setting auth_type to config.

  2. How to create new users in MySQL and control their permissions for better security.

  3. How to generate sitemaps dynamically using PHP.

  4. How to perform simple SELECT statements in SQL to communicate with SQL databases.

More in: MySQL

Skip to content

Today, We want to share with you mysql failed to open file error 2.In this post we will show you mysql> source, hear for failed to open file desktop mysqlsampledatabase sql error 2 we will give you demo and example for implement.In this post, we will learn about Localhost Phpmyadmin Server Error Solution with an example.

mysql: SOURCE error 2?

ERROR: Failed to open file ‘C:UsersPuspakASharmaTEST.SQL’, error: 2

In short, you got the path wrong.

Failed to open file error: 2

Failed to open file , error: 2

Set in Windows:

Example 3:

USE bank;

SOURCE D:/Welcome/4cgandhi/SQL/Tamilrokers/Cookbook/recipes/tables/api_v1.sql;

Alternatively, you can use escaped back slashes:

SOURCE D:\Welcome\4cgandhi\SQL\Tamilrokers\Cookbook\recipes\tables\api_v1.sql;

I hope you get an idea about mysql source command.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Subscribe On YouTube : Download Source Code

Nitro84

0 / 0 / 0

Регистрация: 06.02.2015

Сообщений: 46

1

MySQL

07.07.2015, 12:23. Показов 8457. Ответов 6

Метки нет (Все метки)


Использую ключевое слово SOURCE для чтения запроса из файла.
1. Захожу в свою базу данных

SQL
1
C:>mysql -h localhost -uuser -p

2.

SQL
1
USE cookbook;

3.

SQL
1
SOURCE d:NitroтестированиеSQLBooks_mysqlCookbookrecipesTABLEScow.sql

После этого вываливается ошибка ERROR: Failed to open file ‘ d:NitroтестированиеSQLBooks_mysqlCookbookrec ipestablescow.sql’ , error: 2

помогите решить проблему

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



14 / 14 / 13

Регистрация: 03.07.2015

Сообщений: 130

07.07.2015, 13:46

2



0



0 / 0 / 0

Регистрация: 06.02.2015

Сообщений: 46

07.07.2015, 14:07

 [ТС]

3

поточнее,а то не совсем понятно



0



14 / 14 / 13

Регистрация: 03.07.2015

Сообщений: 130

07.07.2015, 14:09

4

Ну ты же импорт из файла хочешь сделать?



0



0 / 0 / 0

Регистрация: 06.02.2015

Сообщений: 46

07.07.2015, 14:16

 [ТС]

5

ну да, только указывая путь с этим файлом — получается ошибка



0



14 / 14 / 13

Регистрация: 03.07.2015

Сообщений: 130

07.07.2015, 14:19

6

Попробуй букву диска в верхний регистр d -> D
Так же, возможно, ругается на рашн-символы



1



0 / 0 / 0

Регистрация: 06.02.2015

Сообщений: 46

07.07.2015, 14:33

 [ТС]

7

Спасибо, действительно на русский получается вываливается ошибка. Регистр не при чем.
Все остается так же просто поменял название тестирование на testing и все прокатило.



0



Понравилась статья? Поделить с друзьями:
  • Error failed to open display
  • Error failed to open apk database permission denied
  • Error failed to mount fridge error 0x2 windows 10
  • Error failed to mount dev loop0
  • Error failed to lookup view error in views directory