My cnf mysql где находится windows

My computer is Windows XP. I need to find my.cnf to get all privileges back to the root user. I accidentally removed some privileges of the root user. I still have the password and there is no pr...

My computer is Windows XP.

I need to find my.cnf to get all privileges back to the root user. I accidentally removed some privileges of the root user. I still have the password and there is no problem for me to log in to MySQL as the root user. But I can not alter a table.

Eric Leschinski's user avatar

asked Nov 11, 2009 at 2:32

Steven's user avatar

0

Here is my answer:

  1. Win+R (shortcut for ‘run’), type services.msc, Enter
  2. You should find an entry like ‘MySQL56’, right click on it, select properties
  3. You should see something like "D:/Program Files/MySQL/MySQL Server 5.6/binmysqld" --defaults-file="D:ProgramDataMySQLMySQL Server 5.6my.ini" MySQL56

Full answer here:
https://stackoverflow.com/a/20136523/1316649

Richard's user avatar

Richard

4,2735 gold badges31 silver badges53 bronze badges

answered Nov 23, 2013 at 2:04

fstang's user avatar

fstangfstang

5,2064 gold badges24 silver badges25 bronze badges

1

To answer your question, on Windows, the my.cnf file may be called my.ini. MySQL looks for it in the following locations (in this order):

  • %PROGRAMDATA%MySQLMySQL Server 5.7my.ini, %PROGRAMDATA%MySQLMySQL Server 5.7my.cnf
  • %WINDIR%my.ini, %WINDIR%my.cnf
  • C:my.ini, C:my.cnf
  • INSTALLDIRmy.ini, INSTALLDIRmy.cnf

See also http://dev.mysql.com/doc/refman/5.7/en/option-files.html

Then you can edit the config file and add an entry like this:

[mysqld]
skip-grant-tables

Then restart the MySQL Service and you can log in and do what you need to do. Of course you want to disable that entry in the config file as soon as possible!

See also http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

Zitrax's user avatar

Zitrax

18.3k19 gold badges85 silver badges107 bronze badges

answered Nov 11, 2009 at 2:46

Bill Karwin's user avatar

Bill KarwinBill Karwin

525k85 gold badges652 silver badges815 bronze badges

2

Windows 7 location is: C:UsersAll UsersMySQLMySQL Server 5.5my.ini

For XP may be: C:Documents and SettingsAll UsersMySQLMySQL Server 5.5my.ini

At the tops of these files are comments defining where my.cnf can be found.

Eric Leschinski's user avatar

answered May 23, 2013 at 15:30

Alberto's user avatar

AlbertoAlberto

1311 silver badge4 bronze badges

1

You can find the basedir (and within maybe your my.cnf) if you do the following query in your mysql-Client (e.g. phpmyadmin)

SHOW VARIABLES

marc_s's user avatar

marc_s

721k173 gold badges1320 silver badges1442 bronze badges

answered Feb 18, 2014 at 15:24

digitaldonkey's user avatar

digitaldonkeydigitaldonkey

2,4311 gold badge20 silver badges16 bronze badges

you can search this file : resetroot.bat

just double click it so that your root accout will be reset and all the privileges are turned into YES

answered Nov 11, 2009 at 2:43

Treby's user avatar

TrebyTreby

1,3206 gold badges18 silver badges26 bronze badges

Start->Search->For Files and Folders->All Files and Folders

type «my.cnf» and hit search.

answered Nov 11, 2009 at 2:36

Jeremy Morgan's user avatar

0

Существует ли команда MySQL для поиска конфигурационного файла my.cnf подобно тому, как phpinfo() в PHP находит php.ini?

Ответ 1

Не существует внутренней команды MySQL для отслеживания этого, это слишком абстрактно. Файл может находиться в 5 (и более) местах, и все они будут действительными, поскольку загружаются каскадно:

  1. /etc/my.cnf

  2. /etc/mysql/my.cnf

  3. $MYSQL_HOME/my.cnf

  4. [datadir]/my.cnf

  5. ~/.my.cnf

Это места по умолчанию, на которые MySQL обращает внимание. Если он находит более одного варианта, он загружает каждый из них, и значения переопределяют друг друга (в перечисленном порядке). Кроме того, параметр —defaults-file может отменить все эти варианты. Но благодаря тому, что все так запутано, есть большая вероятность, что это просто может быть /etc/my.cnf (если вы просто хотите посмотреть значения используйте значение в SHOW VARIABLES, но для этого вам понадобятся права доступа).

Ответ 2

На самом деле, вы можете «запросить» у MySQL список всех мест, где он ищет my.cnf (или my.ini в Windows). Однако это не SQL-запрос. Просто выполните команду:

$ mysqladmin —help

Или для версии 5.7:

$ mysqld —help —verbose

В самых первых строках ответа вы найдете сообщение со списком всех мест my.cnf. На моей машине это:

 Параметры по умолчанию считываются из следующих файлов в указанном порядке:

/etc/my.cnf

/etc/mysql/my.cnf

/usr/etc/my.cnf

~/.my.cnf

Или для Windows:

Параметры по умолчанию считываются из следующих файлов в указанном порядке:

C:Windowsmy.ini

C:Windowsmy.cnf

C:my.ini

C:my.cnf

C:Program FilesMySQLMySQL Server 5.5my.ini

C:Program FilesMySQLMySQL Server 5.5my.cnf

 Обратите внимание, что может случиться так, что ни в одном из этих мест не окажется файла my.cnf. Поэтому вы можете создать файл самостоятельно — используйте один из образцов конфигурационных файлов, поставляемых с дистрибутивом MySQL (в Linux смотрите файлы /usr/share/mysql/*.cnf и используйте тот, который подходит вам — скопируйте его в /etc/my.cnf, а затем измените по необходимости).

Также обратите внимание, что существует опция командной строки —defaults-file, которая может определить собственный путь к файлу my.cnf или my.ini. Например, для MySQL 5.5 на Windows это указывает на файл my.ini в каталоге данных, который обычно не указывается в mysqld —help —verbose. В Windows посмотрите свойства службы, чтобы выяснить, так ли это в вашем случае.

Наконец, проверьте сайт https://dev.mysql.com/doc/refman/8.0/en/option-files.html там все описано более подробно.

Ответ 3

mysql —help | grep /my.cnf | xargs ls

 Эта команда подскажет вам, где находится my.cnf на Mac/Linux:

ls: cannot access ‘/etc/my.cnf’: Нет такого файла или каталога

ls: cannot access ‘~/.my.cnf’: Нет такого файла или каталога

 /etc/mysql/my.cnf

 В данном случае он находится в файле /etc/mysql/my.cnf.

 Ответ 4

Это может сработать:

strace mysql «;» 2>&1  | grep cnf

 На моей машине этот код выводит:

stat64(«/etc/my.cnf», 0xbf9faafc)       = -1 ENOENT (No such file or directory)

stat64(«/etc/mysql/my.cnf», {st_mode=S_IFREG|0644, st_size=4271, …}) = 0

open(«/etc/mysql/my.cnf», O_RDONLY|O_LARGEFILE) = 3

read(3, «# /etc/mysql/my.cnf: The global «…, 4096) = 4096

stat64(«/home/xxxxx/.my.cnf», 0xbf9faafc) = -1 ENOENT (No such file or directory)

Таким образом, похоже, что /etc/mysql/my.cnf то, что надо, поскольку stat64() и read() были выполнены успешно.

Ответ 5

По умолчанию mysql ищет my.cnf сначала в папке /etc. Если в этой папке нет файла /etc/my.cnf, я советую вам создать новый файл в следующей папке, как указано в документации (https://dev.mysql.com/doc/refman/5.6/en/option-files.html).

Вы также можете поискать существующий my.cnf в вашей установке mysql.  Для этого запустите следующую команду:

sudo find / -name «*.cnf»

Вы можете использовать следующий конфигурационный файл с таблицей myisam и без поддержки innodb mysql (из установки порта mysql на mac os x maverick). Пожалуйста, проверьте каждую команду в этом конфигурационном файле.

# Пример конфигурационного файла MySQL для большинства систем.

#

# Это работает для большой системы с памятью = 512M, в которой работает в основном

# MySQL.

#

# Программы MySQL ищут файлы опций в нескольких

# местах, которые зависят от платформы развертывания.

# Вы можете скопировать этот файл опций в одно из этих мест. Информацию об этих местах см:

# http://dev.mysql.com/doc/mysql/en/option-files.html

#

# В этом файле вы можете использовать все опции, которые поддерживает программа.

# Если вы хотите узнать, какие опции поддерживает программа, запустите программу

# с опцией «—help».

# Следующие опции будут передаваться всем клиентам MySQL

 [client]

#password   = your_password

port        = 3306

socket      = /opt/local/var/run/mysql5/mysqld.sock

# Далее следуют записи для некоторых конкретных программ

# The MySQL server

[mysqld]

port        = 3306

socket      = /opt/local/var/run/mysql5/mysqld.sock

skip-locking

key_buffer_size = 256M

max_allowed_packet = 1M

table_open_cache = 256

sort_buffer_size = 1M

read_buffer_size = 1M

read_rnd_buffer_size = 4M

myisam_sort_buffer_size = 64M

thread_cache_size = 8

query_cache_size= 16M

# Try number of CPU’s*2 for thread_concurrency

thread_concurrency = 8

# Не следует прослушивать порт TCP/IP. Это может повысить безопасность,

# если все процессы, которым нужно подключиться к mysqld, работают на одном хосте.

# Все взаимодействие с mysqld должно осуществляться через сокеты Unix или именованные каналы.

# Обратите внимание, что использование этой опции без включения именованных труб в Windows

# (с помощью опции «enable-named-pipe») сделает mysqld бесполезным!

#skip-networking

# Replication Master Server (по умолчанию)

# Для репликации требуется двоичное протоколирование

log-bin=mysql-bin

# двоичный формат протоколирования рекомендуется смешанный режим

binlog_format=mixed

# требуемый уникальный идентификатор от 1 до 2^32 — 1

# значение по умолчанию равно 1, если master-host не установлен

# но не будет функционировать как мастер, если пропущено

server-id   = 1

# Replication Slave (закомментируйте раздел master, чтобы использовать это)

#

# Чтобы настроить этот хост в качестве ведомого устройства репликации, вы можете выбрать между

# двумя методами:

#

# 1) Использовать команду CHANGE MASTER TO (полностью описана в нашем руководстве) — #

# синтаксис следующий:

#

#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,

#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;

#

# где <host>, <user>, <password> заменяются строками в кавычках, а

# <port> номером порта мастера (по умолчанию 3306).

#

#    Пример:

#

#    CHANGE MASTER TO MASTER_HOST=’125.564.12.1′, MASTER_PORT=3306,

#    MASTER_USER=’joe’, MASTER_PASSWORD=’secret’;

#

# ИЛИ

#

# 2) Установите переменные, указанные ниже. Однако в случае, если вы выберете этот метод, то

# запустите репликацию в первый раз (даже неудачно, например,

# если вы неправильно ввели пароль в master-password и ведомому не удается

# подключиться), ведомый создаст файл master.info, и любые последующие

# изменения в этом файле значений переменных ниже будут проигнорированы и

# отменяться содержимым файла master.info, если вы не выключите

# ведомый сервер, удалите файл master.info и перезапустите ведомый сервер.

# По этой причине вы можете оставить приведенные ниже строки нетронутыми

# (закомментированные) и вместо них использовать CHANGE MASTER TO (см. выше)

#

# требуется уникальный идентификатор от 2 до 2^32 — 1

# (и отличный от master)

# по умолчанию равен 2, если установлен master-host

# но не будет функционировать как ведомое устройство, если пропущено

#server-id       = 2

#

# Мастер репликации для этого ведомого обязательный параметр

#master-host     =   <hostname>

#

# Имя пользователя, которое ведомый будет использовать для аутентификации при подключении

# к ведущему устройству обязательный параметр

#master-user     =   <username>

#

# Пароль, с которым ведомый будет аутентифицироваться при подключении к

# ведущим обязательный параметр

#master-password =   <password>

#

# Порт, на котором прослушивается мастер,

# необязательный параметр по умолчанию 3306

#master-port     =  <port>

#

# двоичное протоколирование не требуется для ведомых, но рекомендуется установить

#log-bin=mysql-bin

# Не комментируйте следующее, если вы используете таблицы InnoDB

#innodb_data_home_dir          = /opt/local/var/db/mysql5

#innodb_data_file_path           = ibdata1:10M:autoextend

#innodb_log_group_home_dir = /opt/local/var/db/mysql5

# Вы можете установить .._buffer_pool_size до 50 — 80 %

# оперативной памяти, но остерегайтесь слишком большого использования памяти.

#innodb_buffer_pool_size                 = 256M

#innodb_additional_mem_pool_size = 20M

# Установите размер .._log_file_size на 25 % от размера буферного пула

#innodb_log_file_size                    = 64M

#innodb_log_buffer_size                = 8M

#innodb_flush_log_at_trx_commit = 1

#innodb_lock_wait_timeout            = 50

[mysqldump]

quick

max_allowed_packet = 16M

[mysql]

no-auto-rehash

# Удалите следующий символ комментария, если вы не знакомы с SQL

#safe-updates

[myisamchk]

key_buffer_size = 128M

sort_buffer_size = 128M

read_buffer        = 2M

write_buffer       = 2M

[mysqlhotcopy]

interactive-timeout

I’m running MySQL Server 5.6 on Windows 7 and would like to enable slow query logging. Unfortunately, it is not immediately obvious to me where the my.cnf file is.

I see C:Program FilesMySQLMySQL Server 5.6my-default.ini but according to that…

# *** DO NOT EDIT THIS FILE. It's a template which will be copied to the
# *** default location during install, and will be replaced if you
# *** upgrade to a newer version of MySQL.

I don’t see any my.cnf or my.ini file in C:UsersneubertAppDataRoamingMySQL either.

Any ideas?

asked Jan 22, 2016 at 4:35

neubert's user avatar

Here’s the location with MySQL Server 5.7:

C:ProgramDataMySQLMySQL Server 5.7my.ini

answered Apr 2, 2017 at 21:28

neubert's user avatar

neubertneubert

6,39332 gold badges73 silver badges132 bronze badges

If an ini file exists it will be in

c:Windows

It’s typically named

my.ini

answered Jan 22, 2016 at 20:07

Dave's user avatar

DaveDave

2662 silver badges7 bronze badges

There is no internal MySQL command to trace this, it’s a little too abstract. The file might be in 5 (or more?) locations, and they would all be valid because they load cascading.

  • /etc/my.cnf
  • /etc/mysql/my.cnf
  • $MYSQL_HOME/my.cnf
  • [datadir]/my.cnf
  • ~/.my.cnf

Those are the default locations MySQL looks at. If it finds more than one, it will load each of them & values override each other (in the listed order, I think). Also, the --defaults-file parameter can override the whole thing, so… basically, it’s a huge pain in the butt.

But thanks to it being so confusing, there’s a good chance it’s just in /etc/my.cnf.

(If you just want to see the values: SHOW VARIABLES, but you’ll need the permissions to do so.)

Run mysql --help and you will see:

Default options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf

enter image description here

Avatar's user avatar

Avatar

14k8 gold badges116 silver badges190 bronze badges

answered Mar 21, 2010 at 3:12

tadamson's user avatar

tadamsontadamson

8,4711 gold badge19 silver badges9 bronze badges

14

You can actually «request» MySQL for a list of all locations where it searches for my.cnf (or my.ini on Windows). It is not an SQL query though. Rather, execute:

$ mysqladmin --help

or, prior 5.7:

$ mysqld --help --verbose

In the very first lines you will find a message with a list of all my.cnf locations it looks for. On my machine it is:

Default options are read from the following files in the given order:
/etc/my.cnf
/etc/mysql/my.cnf
/usr/etc/my.cnf
~/.my.cnf

Or, on Windows:

Default options are read from the following files in the given order:
C:Windowsmy.ini
C:Windowsmy.cnf
C:my.ini
C:my.cnf
C:Program FilesMySQLMySQL Server 5.5my.ini
C:Program FilesMySQLMySQL Server 5.5my.cnf

Note however, that it might be the case that there is no my.cnf file at any of these locations. So, you can create the file on your own — use one of the sample config files provided with MySQL distribution (on Linux — see /usr/share/mysql/*.cnf files and use whichever is appropriate for you — copy it to /etc/my.cnf and then modify as needed).

Also, note that there is also a command line option --defaults-file which may define custom path to my.cnf or my.ini file. For example, this is the case for MySQL 5.5 on Windows — it points to a my.ini file in the data directory, which is not normally listed with mysqld --help --verbose. On Windows — see service properties to find out if this is the case for you.

Finally, check the https://dev.mysql.com/doc/refman/8.0/en/option-files.html — it is described there in more details.

wibeasley's user avatar

wibeasley

4,8503 gold badges33 silver badges61 bronze badges

answered Mar 7, 2012 at 14:22

Tim's user avatar

TimTim

12k7 gold badges50 silver badges70 bronze badges

7

You could always run find in a terminal.

find / -name my.cnf

answered Mar 20, 2010 at 9:06

Dyllon's user avatar

DyllonDyllon

1,2317 silver badges5 bronze badges

6

mysql --help | grep /my.cnf | xargs ls

will tell you where my.cnf is located on Mac/Linux

ls: cannot access '/etc/my.cnf': No such file or directory
ls: cannot access '~/.my.cnf': No such file or directory
 /etc/mysql/my.cnf

In this case, it is in /etc/mysql/my.cnf

ls: /etc/my.cnf: No such file or directory
ls: /etc/mysql/my.cnf: No such file or directory
ls: ~/.my.cnf: No such file or directory
/usr/local/etc/my.cnf

In this case, it is in /usr/local/etc/my.cnf

answered Jul 6, 2019 at 14:35

kimbaudi's user avatar

kimbaudikimbaudi

12.5k8 gold badges59 silver badges68 bronze badges

3

You can use :

locate my.cnf
whereis my.cnf
find . -name my.cnf

suspectus's user avatar

suspectus

16.2k8 gold badges48 silver badges56 bronze badges

answered Feb 27, 2013 at 8:19

Satish Sharma's user avatar

Satish SharmaSatish Sharma

3,2649 gold badges37 silver badges51 bronze badges

3

This might work:

strace mysql ";" 2>&1  | grep cnf

on my machine this outputs:

stat64("/etc/my.cnf", 0xbf9faafc)       = -1 ENOENT (No such file or directory)
stat64("/etc/mysql/my.cnf", {st_mode=S_IFREG|0644, st_size=4271, ...}) = 0
open("/etc/mysql/my.cnf", O_RDONLY|O_LARGEFILE) = 3
read(3, "# /etc/mysql/my.cnf: The global "..., 4096) = 4096
stat64("/home/xxxxx/.my.cnf", 0xbf9faafc) = -1 ENOENT (No such file or directory)

So it looks like /etc/mysql/my.cnf is the one since it stat64() and read() were successful.

answered Mar 22, 2010 at 18:13

Chuck Ross's user avatar

Chuck RossChuck Ross

3062 silver badges2 bronze badges

0

By default, mysql search my.cnf first at /etc folder. If there is no /etc/my.cnf file inside this folder, I advise you to create new one in this folder as indicated by the documentation (https://dev.mysql.com/doc/refman/5.6/en/option-files.html).

You can also search for existing my.cnf furnished by your mysql installation. You can launch the following command

sudo find / -name "*.cnf"

You can use the following configuration file with myisam table and without innodb mysql support (from port installation of mysql on mac os x maverick). Please verify each command in this configuration file.

# Example MySQL config file for large systems.
#
# This is for a large system with memory = 512M where the system runs mainly
# MySQL.
#
# MySQL programs look for option files in a set of
# locations which depend on the deployment platform.
# You can copy this option file to one of those
# locations. For information about these locations, see:
# http://dev.mysql.com/doc/mysql/en/option-files.html
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.

# The following options will be passed to all MySQL clients
[client]
#password   = your_password
port        = 3306
socket      = /opt/local/var/run/mysql5/mysqld.sock

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port        = 3306
socket      = /opt/local/var/run/mysql5/mysqld.sock
skip-locking
key_buffer_size = 256M
max_allowed_packet = 1M
table_open_cache = 256
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 4M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size= 16M
# Try number of CPU's*2 for thread_concurrency
thread_concurrency = 8

# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
# 
#skip-networking

# Replication Master Server (default)
# binary logging is required for replication
log-bin=mysql-bin

# binary logging format - mixed recommended
binlog_format=mixed

# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id   = 1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
#    the syntax is:
#
#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
#    where you replace <host>, <user>, <password> by quoted strings and
#    <port> by the master's port number (3306 by default).
#
#    Example:
#
#    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
#    MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
#    start replication for the first time (even unsuccessfully, for example
#    if you mistyped the password in master-password and the slave fails to
#    connect), the slave will create a master.info file, and any later
#    change in this file to the variables' values below will be ignored and
#    overridden by the content of the master.info file, unless you shutdown
#    the slave server, delete master.info and restart the slaver server.
#    For that reason, you may want to leave the lines below untouched
#    (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id       = 2
#
# The replication master for this slave - required
#master-host     =   <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user     =   <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password =   <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port     =  <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin

# Uncomment the following if you are using InnoDB tables
#innodb_data_home_dir = /opt/local/var/db/mysql5
#innodb_data_file_path = ibdata1:10M:autoextend
#innodb_log_group_home_dir = /opt/local/var/db/mysql5
# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
#innodb_buffer_pool_size = 256M
#innodb_additional_mem_pool_size = 20M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size = 64M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[myisamchk]
key_buffer_size = 128M
sort_buffer_size = 128M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout

answered Mar 20, 2014 at 9:58

Ranaivo's user avatar

RanaivoRanaivo

1,56812 silver badges6 bronze badges

For Ubuntu 16: /etc/mysql/mysql.conf.d/mysqld.cnf

answered Jul 3, 2017 at 10:55

Edmunds22's user avatar

Edmunds22Edmunds22

6608 silver badges10 bronze badges

1

As noted by konyak you can get the list of places mysql will look for your my.cnf file by running mysqladmin --help. Since this is pretty verbose you can get to the part you care about quickly with:

$ mysqladmin --help | grep -A1 'Default options'

This will give you output similar to:

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

Depending on how you installed mysql it is possible that none of these files are present yet. You can cat them in order to see how your config is being built and create your own my.cnf if needed at your preferred location.

answered Dec 15, 2015 at 7:18

Matt Sanders's user avatar

Matt SandersMatt Sanders

6,6732 gold badges30 silver badges46 bronze badges

2

I don’t know how you’ve setup MySQL on your Linux environment but have you checked?

  • /etc/my.cnf

answered Mar 20, 2010 at 7:00

Buhake Sindi's user avatar

Buhake SindiBuhake Sindi

86.9k28 gold badges167 silver badges224 bronze badges

0

Try running mysqld --help --verbose | grep my.cnf | tr " " "n"

Output will be something like

/etc/my.cnf
/etc/mysql/my.cnf
/usr/local/etc/my.cnf
~/.my.cnf

answered Jun 2, 2016 at 21:18

Abram's user avatar

AbramAbram

39k26 gold badges131 silver badges178 bronze badges

1

You can also run this command.

mysql --help | grep cnf

answered Jun 11, 2019 at 18:31

prafi's user avatar

prafiprafi

8919 silver badges11 bronze badges

1

If you’re on a Mac with Homebrew, use

brew info mysql

You’ll see something like

$ brew info mysql
mysql: stable 5.6.13 (bottled)
http://dev.mysql.com/doc/refman/5.6/en/
Conflicts with: mariadb, mysql-cluster, percona-server
/usr/local/Cellar/mysql/5.6.13 (9381 files, 354M) *

That last line is the INSTALLERDIR per the MySQL docs

answered Aug 6, 2013 at 14:28

New Alexandria's user avatar

New AlexandriaNew Alexandria

6,7394 gold badges56 silver badges77 bronze badges

Be aware that although mariadDB loads configuration details from the various my.cnf files as listed in the other answers here, it can also load them from other files with different names.

That means that if you make a change in one of the my.cnf files, it may get overwritten by another file of a different name. To make the change stick, you need to change it in the right (last loaded) config file — or, maybe, change it in all of them.

So how do you find all the config files that might be loaded? Instead of looking for my.cnf files, try running:

grep -r datadir /etc/mysql/

This will find all the places in which datadir is mentioned. In my case, it produces this answer:

/etc/mysql/mariadb.conf.d/50-server.cnf:datadir     = /var/lib/mysql 

When I edit that file (/etc/mysql/mariadb.conf.d/50-server.cnf) to change the value for datadir, it works, whereas changing it in my.cnf does not. So whatever option you are wanting to change, try looking for it this way.

answered Mar 26, 2020 at 20:43

Noel Swanson's user avatar

1

If you are on Debian/Ubuntu system and already equipped with modern versions of the database (everything from 5.7 up, also true for mysql 8) the best way to locate the actual .cnf file I have found is:

sudo update-alternatives --config my.cnf

You should see a output like this:

There are 3 choices for the alternative my.cnf (providing /etc/mysql/my.cnf).

  Selection    Path                        Priority   Status
------------------------------------------------------------
  0            /etc/mysql/mariadb.cnf       500       auto mode
  1            /etc/mysql/mariadb.cnf       500       manual mode
  2            /etc/mysql/my.cnf.fallback   100       manual mode
* 3            /etc/mysql/mysql.cnf         300       manual mode

There are two lines in /etc/mysql/mysql.cnf that it makes sense to pay attention to:

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

MySQL will go watching for all .cnf files in /etc/mysql/conf.d/, then all files in /etc/mysql/mysql.conf.d/

Happy tuning!

answered Mar 26, 2022 at 10:17

coocheenin's user avatar

1

Found mine using

mysqld --help --verbose | grep my.cnf

answered May 19, 2017 at 9:23

phaberest's user avatar

phaberestphaberest

3,0813 gold badges33 silver badges40 bronze badges

Answered for only MySQL Workbench users,

enter image description here

answered Jul 3, 2017 at 11:46

MAX's user avatar

MAXMAX

1,5444 gold badges17 silver badges25 bronze badges

1

Another option is to use the whereis command.

E.g. whereis my.cnf

answered Mar 23, 2012 at 11:06

jbatista's user avatar

jbatistajbatista

9902 gold badges11 silver badges26 bronze badges

1

I installed xampp bundle with apache, php and mysql in ubuntu. There my.cnf file is located in /opt/lampp/etc/ folder. Hope it’ll help somebody.

answered Nov 16, 2015 at 11:31

Mahendran Sakkarai's user avatar

All great suggestions, in my case I didn’t find it in any of those locations, but in /usr/share/mysql, I have a RHEL VM and I installed mysql5.5

Maqbool's user avatar

Maqbool

1772 silver badges9 bronze badges

answered Jul 26, 2014 at 18:26

Roland's user avatar

You will have to look through the various locations depending on your version of MySQL.

mysqld --help -verbose | grep my.cnf

For Homebrew:
/usr/local/Cellar/mysql/8.0.11/bin/mysqld (mysqld 8.0.11)

Default possible locations:
/etc/my.cnf
/etc/mysql/my.cnf
~/.my.cnf

Found mine here: 
/usr/local/etc/my.cnf

answered Jul 8, 2018 at 23:53

Rob's user avatar

RobRob

3383 silver badges5 bronze badges

0

On Ubuntu (direct edit) :

$ sudo nano /etc/mysql.conf.d/mysqld.cnf

answered May 9, 2019 at 12:34

1

In case you are in a VPS and are trying to edit a my.cnf on an already running server you could try:

ps aux | grep mysql

You will be show the parameters the mysql command is being run and where the --defaults-file points to

Note that your server might be running more than one MySQL/MariaDB server’s. If you see a line without --defaults-file parameter, that instance might be retrieving the configuration from the .cnf’s that are mentioned on mysqladmin --help as others have pointed out.

answered Jan 29, 2020 at 23:47

Sdlion's user avatar

SdlionSdlion

5158 silver badges18 bronze badges

You can find my.cnf or any other file with find command:

find / -name my.cnf (or any other file name)
  1. find is a command
  2. / (slash) is a path
  3. my.cnf is a file name

answered Oct 5, 2021 at 9:41

Aleksandar Gordic.'s user avatar

If you are using MAMP, access Templates > MySQL (my.cnf) > [version]

If you are running MAMP windowless you may need to customize the toolbar using the Customize button.

MAMP PRO Templates Menu

answered Jul 26, 2017 at 1:31

Slam's user avatar

SlamSlam

3,0271 gold badge14 silver badges24 bronze badges

for me it was that i had «ENGINE=MyISAM» kind of tables , once i changed it to «ENGINE=InnoDB» it worked:)
in PhpMyAdmin on Azure App Service :)

answered Jan 26, 2019 at 10:50

July's user avatar

JulyJuly

677 bronze badges

It depend on your access right but for me
this work on phpmyadmin sql console

SHOW VARIABLES;

then after to change some variables
you can do

SET GLOBAL max_connections = 1000;

or

SET @@GLOBAL.max_connections = 1000;

give a try

answered Apr 18, 2020 at 4:38

marino andriamialy's user avatar

MySQL configuration file:

/etc/my.cnf

answered May 27, 2021 at 4:55

Mohammad Reza Rohani's user avatar

try

mysql --verbose --help | grep -A 1 "Default options"

Suraj Rao's user avatar

Suraj Rao

29.3k11 gold badges96 silver badges103 bronze badges

answered Dec 17, 2021 at 6:23

Chen Margalit's user avatar

For MariaDB 10.5 on Ubuntu 20.04.4 LTS (Focal Fossa):

# The MariaDB configuration file
#
# The MariaDB/MySQL tools read configuration files in the following order:
# 0. "/etc/mysql/my.cnf" symlinks to this file, reason why all the rest is read.
# 1. "/etc/mysql/mariadb.cnf" (this file) to set global defaults,
# 2. "/etc/mysql/conf.d/*.cnf" to set global options.
# 3. "/etc/mysql/mariadb.conf.d/*.cnf" to set MariaDB-only options.
# 4. "~/.my.cnf" to set user-specific options.
#
# If the same option is defined multiple times, the last one will apply.

answered Mar 3, 2022 at 23:10

steven7mwesigwa's user avatar

steven7mwesigwasteven7mwesigwa

4,8413 gold badges16 silver badges30 bronze badges

There is no internal MySQL command to trace this, it’s a little too abstract. The file might be in 5 (or more?) locations, and they would all be valid because they load cascading.

  • /etc/my.cnf
  • /etc/mysql/my.cnf
  • $MYSQL_HOME/my.cnf
  • [datadir]/my.cnf
  • ~/.my.cnf

Those are the default locations MySQL looks at. If it finds more than one, it will load each of them & values override each other (in the listed order, I think). Also, the --defaults-file parameter can override the whole thing, so… basically, it’s a huge pain in the butt.

But thanks to it being so confusing, there’s a good chance it’s just in /etc/my.cnf.

(If you just want to see the values: SHOW VARIABLES, but you’ll need the permissions to do so.)

Run mysql --help and you will see:

Default options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf

enter image description here

Avatar's user avatar

Avatar

14k8 gold badges116 silver badges190 bronze badges

answered Mar 21, 2010 at 3:12

tadamson's user avatar

tadamsontadamson

8,4711 gold badge19 silver badges9 bronze badges

14

You can actually «request» MySQL for a list of all locations where it searches for my.cnf (or my.ini on Windows). It is not an SQL query though. Rather, execute:

$ mysqladmin --help

or, prior 5.7:

$ mysqld --help --verbose

In the very first lines you will find a message with a list of all my.cnf locations it looks for. On my machine it is:

Default options are read from the following files in the given order:
/etc/my.cnf
/etc/mysql/my.cnf
/usr/etc/my.cnf
~/.my.cnf

Or, on Windows:

Default options are read from the following files in the given order:
C:Windowsmy.ini
C:Windowsmy.cnf
C:my.ini
C:my.cnf
C:Program FilesMySQLMySQL Server 5.5my.ini
C:Program FilesMySQLMySQL Server 5.5my.cnf

Note however, that it might be the case that there is no my.cnf file at any of these locations. So, you can create the file on your own — use one of the sample config files provided with MySQL distribution (on Linux — see /usr/share/mysql/*.cnf files and use whichever is appropriate for you — copy it to /etc/my.cnf and then modify as needed).

Also, note that there is also a command line option --defaults-file which may define custom path to my.cnf or my.ini file. For example, this is the case for MySQL 5.5 on Windows — it points to a my.ini file in the data directory, which is not normally listed with mysqld --help --verbose. On Windows — see service properties to find out if this is the case for you.

Finally, check the https://dev.mysql.com/doc/refman/8.0/en/option-files.html — it is described there in more details.

wibeasley's user avatar

wibeasley

4,8503 gold badges33 silver badges61 bronze badges

answered Mar 7, 2012 at 14:22

Tim's user avatar

TimTim

12k7 gold badges50 silver badges70 bronze badges

7

You could always run find in a terminal.

find / -name my.cnf

answered Mar 20, 2010 at 9:06

Dyllon's user avatar

DyllonDyllon

1,2317 silver badges5 bronze badges

6

mysql --help | grep /my.cnf | xargs ls

will tell you where my.cnf is located on Mac/Linux

ls: cannot access '/etc/my.cnf': No such file or directory
ls: cannot access '~/.my.cnf': No such file or directory
 /etc/mysql/my.cnf

In this case, it is in /etc/mysql/my.cnf

ls: /etc/my.cnf: No such file or directory
ls: /etc/mysql/my.cnf: No such file or directory
ls: ~/.my.cnf: No such file or directory
/usr/local/etc/my.cnf

In this case, it is in /usr/local/etc/my.cnf

answered Jul 6, 2019 at 14:35

kimbaudi's user avatar

kimbaudikimbaudi

12.5k8 gold badges59 silver badges68 bronze badges

3

You can use :

locate my.cnf
whereis my.cnf
find . -name my.cnf

suspectus's user avatar

suspectus

16.2k8 gold badges48 silver badges56 bronze badges

answered Feb 27, 2013 at 8:19

Satish Sharma's user avatar

Satish SharmaSatish Sharma

3,2649 gold badges37 silver badges51 bronze badges

3

This might work:

strace mysql ";" 2>&1  | grep cnf

on my machine this outputs:

stat64("/etc/my.cnf", 0xbf9faafc)       = -1 ENOENT (No such file or directory)
stat64("/etc/mysql/my.cnf", {st_mode=S_IFREG|0644, st_size=4271, ...}) = 0
open("/etc/mysql/my.cnf", O_RDONLY|O_LARGEFILE) = 3
read(3, "# /etc/mysql/my.cnf: The global "..., 4096) = 4096
stat64("/home/xxxxx/.my.cnf", 0xbf9faafc) = -1 ENOENT (No such file or directory)

So it looks like /etc/mysql/my.cnf is the one since it stat64() and read() were successful.

answered Mar 22, 2010 at 18:13

Chuck Ross's user avatar

Chuck RossChuck Ross

3062 silver badges2 bronze badges

0

By default, mysql search my.cnf first at /etc folder. If there is no /etc/my.cnf file inside this folder, I advise you to create new one in this folder as indicated by the documentation (https://dev.mysql.com/doc/refman/5.6/en/option-files.html).

You can also search for existing my.cnf furnished by your mysql installation. You can launch the following command

sudo find / -name "*.cnf"

You can use the following configuration file with myisam table and without innodb mysql support (from port installation of mysql on mac os x maverick). Please verify each command in this configuration file.

# Example MySQL config file for large systems.
#
# This is for a large system with memory = 512M where the system runs mainly
# MySQL.
#
# MySQL programs look for option files in a set of
# locations which depend on the deployment platform.
# You can copy this option file to one of those
# locations. For information about these locations, see:
# http://dev.mysql.com/doc/mysql/en/option-files.html
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.

# The following options will be passed to all MySQL clients
[client]
#password   = your_password
port        = 3306
socket      = /opt/local/var/run/mysql5/mysqld.sock

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port        = 3306
socket      = /opt/local/var/run/mysql5/mysqld.sock
skip-locking
key_buffer_size = 256M
max_allowed_packet = 1M
table_open_cache = 256
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 4M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size= 16M
# Try number of CPU's*2 for thread_concurrency
thread_concurrency = 8

# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
# 
#skip-networking

# Replication Master Server (default)
# binary logging is required for replication
log-bin=mysql-bin

# binary logging format - mixed recommended
binlog_format=mixed

# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id   = 1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
#    the syntax is:
#
#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
#    where you replace <host>, <user>, <password> by quoted strings and
#    <port> by the master's port number (3306 by default).
#
#    Example:
#
#    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
#    MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
#    start replication for the first time (even unsuccessfully, for example
#    if you mistyped the password in master-password and the slave fails to
#    connect), the slave will create a master.info file, and any later
#    change in this file to the variables' values below will be ignored and
#    overridden by the content of the master.info file, unless you shutdown
#    the slave server, delete master.info and restart the slaver server.
#    For that reason, you may want to leave the lines below untouched
#    (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id       = 2
#
# The replication master for this slave - required
#master-host     =   <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user     =   <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password =   <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port     =  <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin

# Uncomment the following if you are using InnoDB tables
#innodb_data_home_dir = /opt/local/var/db/mysql5
#innodb_data_file_path = ibdata1:10M:autoextend
#innodb_log_group_home_dir = /opt/local/var/db/mysql5
# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
#innodb_buffer_pool_size = 256M
#innodb_additional_mem_pool_size = 20M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size = 64M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[myisamchk]
key_buffer_size = 128M
sort_buffer_size = 128M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout

answered Mar 20, 2014 at 9:58

Ranaivo's user avatar

RanaivoRanaivo

1,56812 silver badges6 bronze badges

For Ubuntu 16: /etc/mysql/mysql.conf.d/mysqld.cnf

answered Jul 3, 2017 at 10:55

Edmunds22's user avatar

Edmunds22Edmunds22

6608 silver badges10 bronze badges

1

As noted by konyak you can get the list of places mysql will look for your my.cnf file by running mysqladmin --help. Since this is pretty verbose you can get to the part you care about quickly with:

$ mysqladmin --help | grep -A1 'Default options'

This will give you output similar to:

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

Depending on how you installed mysql it is possible that none of these files are present yet. You can cat them in order to see how your config is being built and create your own my.cnf if needed at your preferred location.

answered Dec 15, 2015 at 7:18

Matt Sanders's user avatar

Matt SandersMatt Sanders

6,6732 gold badges30 silver badges46 bronze badges

2

I don’t know how you’ve setup MySQL on your Linux environment but have you checked?

  • /etc/my.cnf

answered Mar 20, 2010 at 7:00

Buhake Sindi's user avatar

Buhake SindiBuhake Sindi

86.9k28 gold badges167 silver badges224 bronze badges

0

Try running mysqld --help --verbose | grep my.cnf | tr " " "n"

Output will be something like

/etc/my.cnf
/etc/mysql/my.cnf
/usr/local/etc/my.cnf
~/.my.cnf

answered Jun 2, 2016 at 21:18

Abram's user avatar

AbramAbram

39k26 gold badges131 silver badges178 bronze badges

1

You can also run this command.

mysql --help | grep cnf

answered Jun 11, 2019 at 18:31

prafi's user avatar

prafiprafi

8919 silver badges11 bronze badges

1

If you’re on a Mac with Homebrew, use

brew info mysql

You’ll see something like

$ brew info mysql
mysql: stable 5.6.13 (bottled)
http://dev.mysql.com/doc/refman/5.6/en/
Conflicts with: mariadb, mysql-cluster, percona-server
/usr/local/Cellar/mysql/5.6.13 (9381 files, 354M) *

That last line is the INSTALLERDIR per the MySQL docs

answered Aug 6, 2013 at 14:28

New Alexandria's user avatar

New AlexandriaNew Alexandria

6,7394 gold badges56 silver badges77 bronze badges

Be aware that although mariadDB loads configuration details from the various my.cnf files as listed in the other answers here, it can also load them from other files with different names.

That means that if you make a change in one of the my.cnf files, it may get overwritten by another file of a different name. To make the change stick, you need to change it in the right (last loaded) config file — or, maybe, change it in all of them.

So how do you find all the config files that might be loaded? Instead of looking for my.cnf files, try running:

grep -r datadir /etc/mysql/

This will find all the places in which datadir is mentioned. In my case, it produces this answer:

/etc/mysql/mariadb.conf.d/50-server.cnf:datadir     = /var/lib/mysql 

When I edit that file (/etc/mysql/mariadb.conf.d/50-server.cnf) to change the value for datadir, it works, whereas changing it in my.cnf does not. So whatever option you are wanting to change, try looking for it this way.

answered Mar 26, 2020 at 20:43

Noel Swanson's user avatar

1

If you are on Debian/Ubuntu system and already equipped with modern versions of the database (everything from 5.7 up, also true for mysql 8) the best way to locate the actual .cnf file I have found is:

sudo update-alternatives --config my.cnf

You should see a output like this:

There are 3 choices for the alternative my.cnf (providing /etc/mysql/my.cnf).

  Selection    Path                        Priority   Status
------------------------------------------------------------
  0            /etc/mysql/mariadb.cnf       500       auto mode
  1            /etc/mysql/mariadb.cnf       500       manual mode
  2            /etc/mysql/my.cnf.fallback   100       manual mode
* 3            /etc/mysql/mysql.cnf         300       manual mode

There are two lines in /etc/mysql/mysql.cnf that it makes sense to pay attention to:

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

MySQL will go watching for all .cnf files in /etc/mysql/conf.d/, then all files in /etc/mysql/mysql.conf.d/

Happy tuning!

answered Mar 26, 2022 at 10:17

coocheenin's user avatar

1

Found mine using

mysqld --help --verbose | grep my.cnf

answered May 19, 2017 at 9:23

phaberest's user avatar

phaberestphaberest

3,0813 gold badges33 silver badges40 bronze badges

Answered for only MySQL Workbench users,

enter image description here

answered Jul 3, 2017 at 11:46

MAX's user avatar

MAXMAX

1,5444 gold badges17 silver badges25 bronze badges

1

Another option is to use the whereis command.

E.g. whereis my.cnf

answered Mar 23, 2012 at 11:06

jbatista's user avatar

jbatistajbatista

9902 gold badges11 silver badges26 bronze badges

1

I installed xampp bundle with apache, php and mysql in ubuntu. There my.cnf file is located in /opt/lampp/etc/ folder. Hope it’ll help somebody.

answered Nov 16, 2015 at 11:31

Mahendran Sakkarai's user avatar

All great suggestions, in my case I didn’t find it in any of those locations, but in /usr/share/mysql, I have a RHEL VM and I installed mysql5.5

Maqbool's user avatar

Maqbool

1772 silver badges9 bronze badges

answered Jul 26, 2014 at 18:26

Roland's user avatar

You will have to look through the various locations depending on your version of MySQL.

mysqld --help -verbose | grep my.cnf

For Homebrew:
/usr/local/Cellar/mysql/8.0.11/bin/mysqld (mysqld 8.0.11)

Default possible locations:
/etc/my.cnf
/etc/mysql/my.cnf
~/.my.cnf

Found mine here: 
/usr/local/etc/my.cnf

answered Jul 8, 2018 at 23:53

Rob's user avatar

RobRob

3383 silver badges5 bronze badges

0

On Ubuntu (direct edit) :

$ sudo nano /etc/mysql.conf.d/mysqld.cnf

answered May 9, 2019 at 12:34

1

In case you are in a VPS and are trying to edit a my.cnf on an already running server you could try:

ps aux | grep mysql

You will be show the parameters the mysql command is being run and where the --defaults-file points to

Note that your server might be running more than one MySQL/MariaDB server’s. If you see a line without --defaults-file parameter, that instance might be retrieving the configuration from the .cnf’s that are mentioned on mysqladmin --help as others have pointed out.

answered Jan 29, 2020 at 23:47

Sdlion's user avatar

SdlionSdlion

5158 silver badges18 bronze badges

You can find my.cnf or any other file with find command:

find / -name my.cnf (or any other file name)
  1. find is a command
  2. / (slash) is a path
  3. my.cnf is a file name

answered Oct 5, 2021 at 9:41

Aleksandar Gordic.'s user avatar

If you are using MAMP, access Templates > MySQL (my.cnf) > [version]

If you are running MAMP windowless you may need to customize the toolbar using the Customize button.

MAMP PRO Templates Menu

answered Jul 26, 2017 at 1:31

Slam's user avatar

SlamSlam

3,0271 gold badge14 silver badges24 bronze badges

for me it was that i had «ENGINE=MyISAM» kind of tables , once i changed it to «ENGINE=InnoDB» it worked:)
in PhpMyAdmin on Azure App Service :)

answered Jan 26, 2019 at 10:50

July's user avatar

JulyJuly

677 bronze badges

It depend on your access right but for me
this work on phpmyadmin sql console

SHOW VARIABLES;

then after to change some variables
you can do

SET GLOBAL max_connections = 1000;

or

SET @@GLOBAL.max_connections = 1000;

give a try

answered Apr 18, 2020 at 4:38

marino andriamialy's user avatar

MySQL configuration file:

/etc/my.cnf

answered May 27, 2021 at 4:55

Mohammad Reza Rohani's user avatar

try

mysql --verbose --help | grep -A 1 "Default options"

Suraj Rao's user avatar

Suraj Rao

29.3k11 gold badges96 silver badges103 bronze badges

answered Dec 17, 2021 at 6:23

Chen Margalit's user avatar

For MariaDB 10.5 on Ubuntu 20.04.4 LTS (Focal Fossa):

# The MariaDB configuration file
#
# The MariaDB/MySQL tools read configuration files in the following order:
# 0. "/etc/mysql/my.cnf" symlinks to this file, reason why all the rest is read.
# 1. "/etc/mysql/mariadb.cnf" (this file) to set global defaults,
# 2. "/etc/mysql/conf.d/*.cnf" to set global options.
# 3. "/etc/mysql/mariadb.conf.d/*.cnf" to set MariaDB-only options.
# 4. "~/.my.cnf" to set user-specific options.
#
# If the same option is defined multiple times, the last one will apply.

answered Mar 3, 2022 at 23:10

steven7mwesigwa's user avatar

steven7mwesigwasteven7mwesigwa

4,8413 gold badges16 silver badges30 bronze badges

6 ответов

Вот мой ответ:

  • Win + R (ярлык для «run» ), введите services.msc, Enter
  • Вы можете найти запись типа «MySQL56», щелкнуть правой кнопкой мыши по ней, выбрать свойства
  • Вы можете видеть, что «D:/Program Files/MySQL/MySQL Server 5.6/binmysqld» —defaults-file = «D:ProgramDataMySQLMySQL Server 5.6my.ini» MySQL56

Полный ответ здесь:
https://stackoverflow.com/questions/8062496/how-to-change-max-allowed-packet-size

fstang
23 нояб. 2013, в 03:09

Поделиться

Чтобы ответить на ваш вопрос, в Windows, файл my.cnf можно назвать my.ini. MySQL ищет его в следующих местах (в этом порядке):

  • %PROGRAMDATA%MySQLMySQL Server 5.7my.ini, %PROGRAMDATA%MySQLMySQL Server 5.7my.cnf
  • %WINDIR%my.ini, %WINDIR%my.cnf
  • C:my.ini, C:my.cnf
  • INSTALLDIR my.ini, INSTALLDIR my.cnf

См. также http://dev.mysql.com/doc/refman/5.7/en/option-files.html

Затем вы можете отредактировать файл конфигурации и добавить запись следующим образом:

[mysqld]
skip-grant-tables

Затем перезапустите службу MySQL, и вы можете войти и сделать то, что вам нужно. Конечно, вы хотите как можно скорее отключить эту запись в файле конфигурации!

См. также http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

Bill Karwin
11 нояб. 2009, в 03:46

Поделиться

Расположение Windows 7: C:UsersAll UsersMySQLMySQL Server 5.5my.ini

Для XP может быть: C:Documents and SettingsAll UsersMySQLMySQL Server 5.5my.ini

В вершинах этих файлов находятся комментарии, определяющие, где my.cnf можно найти.

Alberto
23 май 2013, в 16:13

Поделиться

Вы можете найти basedir (и, возможно, my.cnf), если вы выполните следующий запрос в своем mysql-клиенте (например, phpmyadmin)

SHOW VARIABLES

digitaldonkey
18 фев. 2014, в 15:53

Поделиться

вы можете найти этот файл: resetroot.bat

просто дважды щелкните его так, чтобы ваш корневой атрибут был reset, и все привилегии превратились в YES

Treby
11 нояб. 2009, в 04:07

Поделиться

Пуск- > Поиск- > Для файлов и папок- > Все файлы и папки

введите «my.cnf» и нажмите «Поиск».

Jeremy Morgan
11 нояб. 2009, в 04:15

Поделиться

Ещё вопросы

  • 1Это утечка памяти?
  • 1Компонент prop не обновляет DOM при изменениях вложенных объектов
  • 0Лучшие практики для хранения выражения
  • 1-XX: OnOutOfMemoryError не работает для java.lang.OutOfMemoryError: невозможно создать новый собственный поток
  • 0XML отображает ноды из определенной категории PHP
  • 1Обменяйте ключ и значение JSON
  • 1Передать идентификатор клиента в код
  • 0Зачем использовать SomeType [1] вместо SomeType * в качестве последнего члена в структурах
  • 1Проблема при отправке объекта JSON с помощью BeanShell PreProcessor
  • 0Регулировка scaleX и scaleY Div с помощью ползунка HTML5
  • 1Передача списка списков в качестве входных данных для scipy.optimize.curve_fit
  • 1Установка Dr. Edit ошибка
  • 0Сервер и клиент на Python и C
  • 0Добавить класс в несколько div в зависимости от события клика
  • 1Сокет-сервер без подключения
  • 1Ожидаемое поведение панд str .isnumeric ()
  • 1Как добавить массив к каждой предыдущей строке в пандах?
  • 0Рут в Yii2 не работает
  • 1Android-приложение с внешним кодом / приложением?
  • 1NullReferenceException При вызове функции класса c # [duplicate]
  • 0win32 C ++ положил изображение на экран
  • 0phpseclib не возвращает результатов даже по простой команде
  • 1Приложение не появляется в Маркете для некоторых устройств
  • 1Как функционально объединить несколько серий Deedle в C #?
  • 1Получите информацию о файле почтового индекса — не от его содержания
  • 0Выбор даты не отображается на входе PHP, созданном внутри цикла for
  • 0JQuery не исчезнет в промежутке
  • 0Обновите таблицу цен с новым значением и полем для записи даты
  • 1Добавление данных в программу, если она существует; еще генерировать случайные данные в Java
  • 0сообщение пытается получить свойство необъекта в codeigniter
  • 1Как установить таймаут на мыльный вызов с помощью ksoap2-android?
  • 1Можно ли использовать параметры OleDBCommand в другом месте, кроме предложения Where?
  • 0Не можете добавить внешний ключ здесь?
  • 1Защищен ли сайт от атак XSS, если нет контента, созданного пользователями?
  • 1ElasticSearch с гнездом ElasticType на интерфейсе
  • 1Получение неверного значения из момента-часового пояса при преобразовании даты в секунды эпохи
  • 0Использование 2 разных скриптов на одном и том же флажке
  • 1VueJs 2 скрыть и показать DIV на одной HTML-странице
  • 0OpenGL 4.1 не работает на Mavericks
  • 0Прокрутка страниц с использованием JavaScript
  • 1Несколько общих осей X в сюжетах plot.ly
  • 1Вложенные операторы if / elif приводят к странным результатам [duplicate]
  • 1Как играть в автоматический звонок на номер в Android?
  • 1Когда мы используем тип ссылки и тип объекта [дубликата]
  • 1просмотр списка андроида nullpointer.exception
  • 1Entity Framework — нет первого варианта кода на веб-сайте asp.net.
  • 0POST работает с использованием JQuery, но не Angularjs
  • 0Деструктор для хеш-таблицы с использованием цепочки
  • 1В чем секрет хостинга пользовательских KML для использования в Google Maps Mobile?


есть ли команда MySQL, чтобы найти my.cnf конфигурационный файл, похожий на то, как PHP phpinfo() обнаруживает php.ini?


4893  


18  

18 ответов:

нет внутренней команды MySQL для отслеживания этого, это немного слишком абстрактно. Файл может быть в 5 (или больше?) местоположения, и все они будут действительны, потому что они загружают каскадирование.

  • / etc / my.cnf
  • / etc / mysql / my.cnf
  • $MYSQL_HOME / my.cnf
  • [datadir] / my.cnf
  • ~/. my. cnf

это места по умолчанию, на которые смотрит MySQL. Если он найдет более одного, он загрузит каждый из них & значения переопределяют друг друга (в указанном порядке, я думаю). Кроме того,--defaults-file параметр может переопределить все это, так что… в принципе, это огромная боль в заднице.

но благодаря тому, что это так запутанно, есть хороший шанс, что это просто в /etc/my.cnf.

(Если вы просто хотите увидеть значения: SHOW VARIABLES, но для этого вам понадобятся разрешения.)

вы можете фактически «запросить» MySQL для списка всех мест, где он ищет my.КНФ (или мои.ini на Windows). Это не SQL-запрос. Скорее, выполните:

$ mysqladmin --help

или до 5.7:

$ mysqld --help --verbose

в самых первых строках вы найдете сообщение со списком всех моих.cnf места он ищет. На моей машине это:

Default options are read from the following files in the given order:
/etc/my.cnf
/etc/mysql/my.cnf
/usr/etc/my.cnf
~/.my.cnf

или, на Windows:

Default options are read from the following files in the given order:
C:Windowsmy.ini
C:Windowsmy.cnf
C:my.ini
C:my.cnf
C:Program FilesMySQLMySQL Server 5.5my.ini
C:Program FilesMySQLMySQL Server 5.5my.cnf

обратите внимание, однако, что это может быть так, что нет мой.cnf файл в любом из этих мест. Итак, вы можете создать файл самостоятельно-используйте один из примеров конфигурационных файлов, поставляемых с дистрибутивом MySQL (на Linux-см. /usr/share/mysql/*.cnf файлы и использовать то, что подходит для вас-скопируйте его в /etc/my.cnf а затем изменить по мере необходимости).

внимание:существует также параметр командной строки --defaults-file который может определить пользовательский путь к моему.CNF или My.ini-файл. Например, это относится к MySQL 5.5 на Windows-это указывает к моему.ini-файл в каталоге данных, который обычно не указан в списке с mysqld --help --verbose. В Windows-см свойства службы, чтобы узнать, если это так для вас.

наконец, проверьте https://dev.mysql.com/doc/refman/8.0/en/option-files.html — это описано там более подробно.

вы всегда можете запустить find в терминале.

find / -name my.cnf

вы можете использовать :

locate my.cnf
whereis my.cnf
find . -name my.cnf

Это может сработать:

strace mysql ";" 2>&1  | grep cnf

на моей машине это выводит:

stat64("/etc/my.cnf", 0xbf9faafc)       = -1 ENOENT (No such file or directory)
stat64("/etc/mysql/my.cnf", {st_mode=S_IFREG|0644, st_size=4271, ...}) = 0
open("/etc/mysql/my.cnf", O_RDONLY|O_LARGEFILE) = 3
read(3, "# /etc/mysql/my.cnf: The global "..., 4096) = 4096
stat64("/home/xxxxx/.my.cnf", 0xbf9faafc) = -1 ENOENT (No such file or directory)

Так это выглядит как /etc/mysql / my.cnf-это тот, поскольку он stat64() и read () были успешными.

по умолчанию, mysql search my.cnf сначала в папке / etc. Если нет /etc / my.cnf файл внутри этой папки, я советую вам создать новый в этой папке, как указано в документации (https://dev.mysql.com/doc/refman/5.6/en/option-files.html).

вы также можете искать существующие my.cnf, предоставленный вашей установкой mysql. Вы можете запустить следующую команду

sudo find / -name "*.cnf"

вы можете использовать следующий файл конфигурации с таблицей myisam и без поддержки innodb mysql (от установки порта mysql на mac os x maverick). Проверьте каждую команду в этом файле конфигурации.

# Example MySQL config file for large systems.
#
# This is for a large system with memory = 512M where the system runs mainly
# MySQL.
#
# MySQL programs look for option files in a set of
# locations which depend on the deployment platform.
# You can copy this option file to one of those
# locations. For information about these locations, see:
# http://dev.mysql.com/doc/mysql/en/option-files.html
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.

# The following options will be passed to all MySQL clients
[client]
#password   = your_password
port        = 3306
socket      = /opt/local/var/run/mysql5/mysqld.sock

# Here follows entries for some specific programs

# The MySQL server
[mysqld]
port        = 3306
socket      = /opt/local/var/run/mysql5/mysqld.sock
skip-locking
key_buffer_size = 256M
max_allowed_packet = 1M
table_open_cache = 256
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 4M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size= 16M
# Try number of CPU's*2 for thread_concurrency
thread_concurrency = 8

# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
# 
#skip-networking

# Replication Master Server (default)
# binary logging is required for replication
log-bin=mysql-bin

# binary logging format - mixed recommended
binlog_format=mixed

# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id   = 1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
#    the syntax is:
#
#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
#    where you replace <host>, <user>, <password> by quoted strings and
#    <port> by the master's port number (3306 by default).
#
#    Example:
#
#    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
#    MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
#    start replication for the first time (even unsuccessfully, for example
#    if you mistyped the password in master-password and the slave fails to
#    connect), the slave will create a master.info file, and any later
#    change in this file to the variables' values below will be ignored and
#    overridden by the content of the master.info file, unless you shutdown
#    the slave server, delete master.info and restart the slaver server.
#    For that reason, you may want to leave the lines below untouched
#    (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id       = 2
#
# The replication master for this slave - required
#master-host     =   <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user     =   <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password =   <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port     =  <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin

# Uncomment the following if you are using InnoDB tables
#innodb_data_home_dir = /opt/local/var/db/mysql5
#innodb_data_file_path = ibdata1:10M:autoextend
#innodb_log_group_home_dir = /opt/local/var/db/mysql5
# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
#innodb_buffer_pool_size = 256M
#innodb_additional_mem_pool_size = 20M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size = 64M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[myisamchk]
key_buffer_size = 128M
sort_buffer_size = 128M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout

как отметил коняк вы можете получить список мест, которые mysql будет искать для вашего под управлением mysqladmin --help. Поскольку это довольно многословно, вы можете быстро добраться до той части, о которой вы заботитесь:

$ mysqladmin --help | grep -A1 'Default options'

это даст вам выход, подобный:

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

в зависимости от того, как вы установили mysql, возможно, что ни один из этих файлов еще не присутствует. Вы можете cat их для того, чтобы увидеть, как ваш конфиг строится и создать свой собственный my.cnf при необходимости в ваше предпочтительное местоположение.

попробуй mysqld --help --verbose | grep my.cnf | tr " " "n"

на выходе будет что-то вроде

/etc/my.cnf
/etc/mysql/my.cnf
/usr/local/etc/my.cnf
~/.my.cnf

Если вы находитесь на Mac с Homebrew, используйте

brew info mysql

вы увидите что-то вроде

$ brew info mysql
mysql: stable 5.6.13 (bottled)
http://dev.mysql.com/doc/refman/5.6/en/
Conflicts with: mariadb, mysql-cluster, percona-server
/usr/local/Cellar/mysql/5.6.13 (9381 files, 354M) *

эта последняя строка —INSTALLERDIRв MySQL docs

Я не знаю, как вы настроили MySQL в своей среде Linux, но вы проверили?

  • / etc / my.cnf

нашел мой с помощью

mysqld --help --verbose | grep my.cnf

для Ubuntu 16:/etc/mysql / mysql.конф.d / mysqld.cnf

другой вариант-использовать команду whereis.

например, где мой.cnf

все отличные предложения, в моем случае я не нашел его ни в одном из этих мест, но в /usr/share/mysql, У меня есть RHEL VM и я установил mysql5.5

Я установил пакет xampp с apache, php and mysql на ubuntu. Там my.cnf файл находится в . Надеюсь, это кому-нибудь поможет.

ответил только для пользователей MySQL Workbench,

enter image description here

Если вы используете MAMP, Шаблоны доступа > MySQL (my.cnf) > [версия]

Если вы используете MAMP windowless, вам может потребоваться настроить панель инструментов с помощью кнопки «настроить».

MAMP PRO Templates Menu

вам придется просматривать различные места в зависимости от вашей версии MySQL.

mysqld --help -verbose | grep my.cnf

For Homebrew:
/usr/local/Cellar/mysql/8.0.11/bin/mysqld (mysqld 8.0.11)

Default possible locations:
/etc/my.cnf
/etc/mysql/my.cnf
~/.my.cnf

Found mine here: 
/usr/local/etc/my.cnf

How to find the mySQL configuration file «my.cnf».

calendar_today

Updated On:

Issue/Introduction

The mySql file can be found in multiple default locations and under various names. e.g.

etc/my.cnf,

/etc/mysql/my.cnf,

/usr/etc/my.cnf,

C:Windowsmy.ini,

C:Windowsmy.cnf,

C:my.ini, C:my.cnf,

C:Program FilesMySQLMySQL Server 5.5my.ini C:Program FilesMySQLMySQL Server 5.5my.cnf.

How can I find the mySql configuration file?

Environment

Release: SDBSFO99000-10.2-Spectrum-Device Based Suite-Server FOC
Component:

Resolution

You can actually ask MySQL to show you the list of all locations where it searches for my.cnf (or my.ini on Windows). It is not an SQL command though. Rather, execute: 

$ mysqld —help —verbose 

In the very first lines you will find a message with a list of all my.cnf locations it looks for. On my machine it is: 

Default options are read from the following files in the given order: 

/etc/my.cnf 

/etc/mysql/my.cnf 

/usr/etc/my.cnf 

~/.my.cnf 

Or, on Windows: 

Default options are read from the following files in the given order: 

C:Windowsmy.ini 

C:Windowsmy.cnf 

C:my.ini 

C:my.cnf 

C:Program FilesMySQLMySQL Server 5.5my.ini C:Program FilesMySQLMySQL Server 5.5my.cnf

Additional Information

Feedback

thumb_up
Yes

thumb_down
No

Понравилась статья? Поделить с друзьями:
  • My cinema u3000hybrid windows 7 64 программы
  • Mvcp140 dll скачать для windows 10
  • My book world edition network storage драйвер windows 10
  • Mvcp120 dll скачать для windows 10
  • Mvcp110 dll скачать для windows 10